There are two general approaches you can take to adding a PHP code snippet to WordPress:
- Directly to your theme – you can place the code snippet directly in a file called functions.php in a child theme
- In a plugin – you can place the code snippet in a plugin
Method 1: Adding Code Snippets Using Child Theme
Now, all that’s left to do is add the code snippet(s) to the new functions.php file in your child theme.
If you’re familiar with FTP, I recommend doing this via FTP for the safest approach (sometimes you might accidentally mistype the code, which can cause problems on your site. FTP lets you quickly fix things).
But if that’s confusing, you can also do it right from your WordPress dashboard:
- Go to Appearance → Theme Editor
- Choose the functions.php file under the Theme Files column
- Paste in your code snippet and save your changes
And that’s it!
Method 2: Adding Code Snippets with Code Snippets plugin
For code snippets that aren’t theme specific, you can use the aptly named Code Snippets plugin.
The snippets that you add here will function identically to the snippets you added with the previous method. The only difference is that your snippets will now remain active even if you switch WordPress themes.
Here’s how to use the plugin:
- Install and activate the free Code Snippets plugin
- Go to Snippets → Add New
- Name your snippet (this name is purely internal and helps you remember it)
- Paste in the code snippet in the Code box
- Scroll down to the bottom of the screen
- Choose the Scope for your snippet (when in doubt, stick with the default Run snippet everywhere option)
- Click Save Changes and Activate
And that’s it! Your snippet is now active.
If you ever need to deactivate or edit the snippet at a later date, you can do that by going to the Snippets → All Snippets area.