Turn That Snippet Into A Plugin

This post is sort of a recap of a talk I gave a couple years ago.

Whenever you get a WordPress code snippet, where do you put it? It’s not uncommon all those bits of code to end up cluttering up the functions.php file of your theme, whether out of habit or suggested by tutorials.

But wouldn’t it be better if all those non-theme snippets were plugins instead? Yes!

As plugins, you can switch/upgrade themes without losing that functionality and toggle the funtionality without editing the theme.

And great news! It’s really easy to turn a snippet into a plugin.

The Snippet

Let’s say this is the snippet we’re working with:

add_filter( 'robots_txt', 'prefix_robots_txt' );
function prefix_robots_txt( $robots ) {
    $robots .= "Disallow: /assets/\n";
    return $robots;

This snippet just appends a line to the virtual robots.txt file – but that’s not really important for this post

Give the Snippet Its Own File

There are 2 options for ‘pluginifying’ the snippet, but they both have the same first step, get that plugin into its own php file.

First, we’ll take that snippet and put it into a php file, say robotstxt-additions.php. Don’t forget the opening <?php tag.



Option #1: The Standard Plugin

For a standard plugin, we need to add a plugin header. Plugin headers are just php comments that WordPress reads for information about the plugin. There are several headers, but the required one is Plugin Name

// Plugin Name: Robots.txt Additions


Then, move robotstxt-additions.php to the plugins folder of your WordPress install. By default that would be wp-content/plugins/.

The plugin file can either be “loose” in the main plugins folder, or in a subfolder. If the plugin has or will have style or script assets, you’ll want to put it in a subfolder.

It’s not required for the folder to match the plugin basename, but it is common convention.

Now you’ll be able to see the plugin listed on the Plugins screen of your WordPress install and activate it.


Option #2: The “Must Use” Plugin

Must-use (mu) plugins are always on, which can be really handy. But there’s also no de/activation switch in the admin.

Since we already have the snippet in a file, all we need to do is put it in the mu-plugins folder. This folder sits right next to the regular plugins folder, but is not included in a default install, so you may have to create it.


It’s important for mu-plugins that they not be in any sub folders. For example
will not work.

You can see mu-plugins on the admin’s plugin screen.


Although plugin headers are not required for mu-plugins, if present they will provide additional information in the admin. In this case the Plugin Name header will be used instead of just the filename.


And there you have it.

One thought on “Turn That Snippet Into A Plugin”

Leave a Reply

Your email address will not be published. Required fields are marked *