WordPress Tip: Using a Must Use Plugin to Add Custom Post Type
One of the biggest tips I think can be given today when developing a theme is to not include the code for a Custom Post Type inside the functions file of the theme. If you are developing for a client then by all means use this tip. If you are developing for selling a theme I would use a normal plugin as MU plugins can be a little awkward for a non-tech savvy user to install
Why do that? I Hear You Cry
Well adding the CPT (Custom Post Type) to your theme essentially theme locks your client or customer. They cannot move to a different theme without losing access to their post type… Not without a whole lot of trouble, especially if they aren’t familiar with coding a CPT.
Must Use Plugin. What’s That?
A lot of people associate Must Use plugins, that is a plugin that is auto activated by WordPress and cannot be disabled from the WordPress admin, with WordPress MU. However they can be used with a normal WordPress install too. To do it just create a plugin as normal & throw it inside the mu-plugins folder in wp-content. If there isn’t one, just create it.
Can I See An Example?
It is exactly the same as a normal plugin, the only exception is that you must only insert a single PHP file into the mu-plugins
directory, it cannot be located in a sub folder as normal plugins can. If you require a sub folder for organization of assets it might be handy to use the following script as an autoloader.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php /* * this file is mu-plugins/my-awesome-plugin.php * * Plugin Name: My Awesome Plugin * Plugin URI: http://return-true.com/ * Description: An awesome but totally pointless plugin * Version: 1.0 * Author: Paul Robinson * Author URI: http://return-true.com */ require WPMU_PLUGIN_DIR.'/my-awesome-plugin/my-next-file.php'; |
Inside my-next-file.php
include the code for your plugin. Do not place it inside the file above, it is just meant to auto load any files you need it to. You can however add other files to load if you would like to separate your plugin code into different files.
It is important to note, if you don’t plan on adding any assets such as images and the like, then you can easily just drop a PHP file to the mu-plugins
directory without using a autoloader.
So there you have it. Now if a client ever decides to ask you to change themes without losing their Custom Post Type and/or Custom Taxonomies you don’t have a nightmare, because all the code is contained in the plugin. Not only that if the client decides to hire anyone else they will thank you for not giving them the same problem. Please, please, please add a friendly note in the top of the theme’s function file though to notify other developers that some theme features are located in a Must Use plugin.