How To Safely Add PHP Code To WordPress

One of the best things about WordPress is how easy it is to modify and extend with plugins and themes. Moreover, it lets you modify wordpress even further by letting you modify the modification that modifies wordpress! That’s a lot of flexibility, and more than often leaves you with more than one approach to things.
A common question is where to put small snippets of PHP that make small modifications to other plugins, such as Events Manager. There’s three recommended ways, each have their pros and cons:

Insert it into your theme functions.php file

Most themes nowadays have a functions.php file, located within your theme folder. This file is a php file that is always loaded when displaying that theme, meaning you can make modifications to that theme by adding code there beneath or above any other code already there. If you don’t have a functions.php file, you can create one and it will be automatically included.

Pros

  • Easy to add small snippets of code
  • Convenient when adding functionality to a theme

Cons

  • Disabling the theme will disable the functions.php
  • If you upgrade your theme, your changes will be lost.

Create a file within mu-plugins folder

This is not so well known, but if you create a folder called mu-plugins inside your wp-content folder (same level as your plugins folder), any php files inserted there will be executed every time and can’t be activated/deactivated. This applies to multisite sites too, the file is executed for any network blog. WordPress calls these plugins “Must Use” plugins, meaning they must be used each time. Therefore, it is often convenient to just create a single php file and add your functions there.

Pros

  • Allows for custom code to be kept away from theme and plugin folders
  • Runs every time, no risk of accidental deactivation
  • Very upgrade-safe, since no plugin, core or theme updates overwrite this folder
  • Allows for plugin info to be displayed in plugin menu (if you provide it, see creating your own plugin below).
  • Shared across all themes

Cons

  • Runs every time, which is not always desired
  • Deactivating is not possible from the admin area, only FTP.
  • Shared across all themes

Create your own plugin file!

You can always add a few lines of information above a php file containing your code and move it to the wordpress plugins folder. Check out events-manager.php or the wordpress codex for an example.

Pros

  • Allows you to activate/deactivate the plugin on demand
  • Allows for contextual info about the plugin to be viewed in plugin pages (although you can also do this with MU plugins if you add this header)
  • Shared across all themes
Cons
  • Can be accidentally deactivated by users with relevant privelages

Which one to choose?

It’s really up to you! I use all three, it really depends on the situation.