When you use WordPress for a while, you will inevitably come across a situation where you need some functionality that is not part of the WordPress core. It could be something like adding a custom shortcode or perhaps you want the ability to add shortcodes inside a widget. Whatever the case may be, the solution is usually to Google what you need. You will usually find a code snippet for the functionality that you want to add. The author of the snippet will normally tell you to add the snippet to your functions.php file. This will work fine but over time this can cause your functions.php file to get bloated. Another thing to consider is that changing your theme without a site specific plugin will cause your custom functionality to be lost.
Now you could copy all your code and paste it to the functions.php file of your new theme but there is a better way. Why not extend the WordPress best practice of separating functionality and style. Instead of adding code to the functions.php file, add it to a site specific plugin. this type of plugin is super easy to create even for beginners.
As a beginner it can be scary to mess around with code and it can be really easy to cause the dreaded white screen of death. All it takes is for you to forget to add a single character to your functions.php file and you will break your site, causing untold panic. You can avoid this if you use a site specific plugin. If there is an error with your code, WordPress will detect it and deactivate your plugin. All you have to do to correct the problem then is to go into your plugin and fix the code. Once you’ve fixed your code, just re-activate your plugin. I highly recommend that beginners create a site specific plugin where they can add custom php code with no worries of breaking their site.
How to create a Site Specific Plugin
1. Create a new folder inside your plugins folder. Make the name unique so that you don’t conflict with anything. I would recommend something like mytheme-site-plugin
2. Inside your mytheme-site-plugin folder, create a file. You can call it whatever you like but I would recommend using the same name as your folder for simplicity. I would recommend mytheme-site-plugin.php.
3. Add the following code to the file mytheme-site-plugin.php.
<?php /* * Plugin Name: My Theme site plugin * Plugin URI: http://wpbasics.org * Description: The plugin is used to store site specific code. Will prevent loss of functionality when the theme is switched * Version: 1.0.0 * Author: WP Basics * Author URI: http://wpbasics.org * License: GPLv2 * * */ // Add PHP code below here
4. Now just head over to the plugins section of your WordPress dashboard and activate your new plugin
That’s it, your done. Now you have a safe place to add your PHP code. You no longer have to be worried that you will break your site if you do something wrong. The worst case scenario is that your plugin will be de-activated.
Credit goes out to Otto. I read about this technique here