There are many times when you want to add some custom PHP code to your website. This could be for many reasons, including to extend the functionality of one of our plugins. There are 2 ways to get this done, one is the quick and risky way and the other is our recommended way.
1. Edit Your Theme functions.php File
This is the obvious and quickest way to add custom PHP code to your website. Simply edit your theme’s function.php file, scroll down to the end of the file and insert your code.
There are a few drawbacks to this method:
- Your functions.php file will be overwritten when your theme is updated, wiping out all your custom PHP!
- You could break your website, causing errors which could prevent your visitors from seeing your content
2. Add Code Snippets (Using a plugin)
We use and recommed the Code Snippets plugin, which is a free plugin from the WordPress.org repo. With over 100,000 active installs and over 180 5-star ratings you know it is a quality plugin.
Download the plugin, upload it to your site and activate it.
Then browse to Snippets -> Add New, where you can add a new PHP code snippet.
You can choose to save changes, or save and activate immediately. You can also choose where to run the code snippet (everywhere, admin, front-end or only once).
Advantanges of using the Code Snippets plugin:
- The user interface has code highlighting for errors and issues in your code
- The code will continue to run when you update or change themes in future.