Creating the Difference

How to safely add code to WordPress

Posted on: 25-09-2018 Last modified: 03-07-2021
Categories: PHP, Snippets Tags:

This website is mostly dedicated to extending and enhancing WordPress core and/or plugins.

In almost all of my posts you will find the sentence “Add this to your functions.php”. Sounds simple enough, but what do I actually mean with that? Simple: you will need to add that code to your WordPress installation using one of the three prefered methods below.

How to savely add code to your WordPress installation?

There are many ways to add code to your WordPress installation. Yet, not all are best practice: they may break other plugins and/or be lost when updating or switching themes. I will explain three most common options:

Option 1:
Adding directly into your theme’s function.php

The easiest way to add coding is by simply pasting the code into the functions.php file in your theme directory. You will need a FTP program and a text editor (like Notepad) for that. A ‘benifit’ to this is, that the added code will be automatically loaded for your current theme. The dowside is, that will only be loaded in the current theme – if you switch themes or when it is updated; your additions will be lost.

Option 2:
Adding php code using the Code Snippets plugin

Install and activate the plugin “Code Snippets” from the WordPress Respository. This will create a safe way to add php code snippets right from within your WordPress Dashboard. It is easy and safe to use. The only downside I can think of is that this plugin needs be activated to use the added snippets.
A benefit to the third option is that it will keep your snippets separate from your other blogs if you are running a WordPress MultiSite installation.

Code Snippets

Option 3:
Adding your code through a custom plugin.

If you want to add your code that does not depend on your theme (option 1) and/or if you have a WP MultSite and want to use your snippets across your network, the best way is to create a custom plugin, bundleing all your code together.

  1. Create a folder stonehenge-custom-snippets
  2. Inside that folder, create a new file: stonehenge-custom-snippets.php
  3. Add this code to the file:
  4. Save the file and upload the folder stonehenge-custom-snippets to /wp-content/plugins
  5. In your WordPress Dashboard, go to Plugins and active the new plugin.
  6. Now you can add all your custom codes below the plugin info in stonehenge-custom-snippets.php.

Next ⇒