When you need to run custom PHP code on your WordPress site often you’re instructed to add it to the active theme’s functions.php file.
The issue with this is that each time the theme is updated you lose the changes made to the functions.php file.
One way around this is to create a child theme – but it still has it’s own limitations, such as the plugins_loaded action hook doesn’t fire because it needs to be called before the theme has loaded.
The answer to this is to create a simple custom plugin that can contain all your custom functions. This way you can update your theme without worrying about loosing any of your customisations.
There are other advantages to this –
- easier to maintain
- version control with the plugin version number
- easier to debug
- separated design and functionality – can be disabled or moved to another site
- Better WSOD (White Screen of Death) protection.
Here’s how to create a custom plugin for your functions.
Want the easy way? Give this sample plugin a go: itsg-custom-functions.zip
- Copy the code below to a new text file and save as a PHP file. You can change the details to suit your site.
For example wpdg-custom-functions.php -
<?php /* Plugin Name: itsupportguides.com custom functions Description: Contains custom functions Version: 1.0.0 Author: IT Support Guides Author URI: itsupportguides.com */
- ZIP the file so you have a ZIP file containing the php file
- Open your WordPress administration (wp-admin)
- Go to Plugins -> Add new
- Click on the ‘Upload Plugin’ button and upload the ZIP file
- Activate the plugin
- You can now maintain all your custom functions from the plugin instead of your theme’s functions.php file. Functions are added below the closing */
TIP: make sure that you do not have the same functions anywhere else – such as the themes function.php file.
Stuck? Have a look at the sample plugin: itsg-custom-functions.zip