Creating a Site Specific Plugin in WordPress

Tutorial

Quick: how do you add a custom function into a theme. If you said ‘add it to your functions.php file’, then you would be correct. But is that really the best way to go about things?

The Problem

Let’s say you’ve customized your site with some pretty fancy functions you’ve added in through the hooks and actions in WordPress. You’re in the process of creating a new theme (or selecting a new one for your site), and once it’s done you upload it and activate it.  All of those functions in your functions.php file? They’re still on your old theme, unable to be useful. You could copy and paste them all into your new theme’s functions file, but I think there’s a better way: a “site specific” plugin.

What is a Site Specific Plugin

A site specific plugin is a plugin written by you (the site owner) and is used to house any custom functionality you’ve added.  Unlike a functions.php file, any code in a plugin will be carried over from one theme to the next – this means you can switch themes at your hearts desire and any customizations will be carried over, regardless of which theme you choose.

Here’s how to create a site-specific plugin.

Step 1

Create a new folder in your WordPress’ plugins folder. You can name it anything you want, but I choose to call it ‘site-plugin’. Do this either on your local development or through your favorite FTP client.

Step 2

Use the code below as a starting point.

<?php
/*
Plugin Name: Plugin Name
Plugin URI:  http://www.pluginurl.dev
Description: Site Plugin to hold funcions used on Your Site.
Version:     1
Author:      Mitch Canter
Author URI:  http://mitchcanter.com
Text Domain: mitch-demo
*/

/**
 * Initialize and run setup options on after_theme_setup hook *
 */
add_action( 'after_setup_theme', 'sitedemo_setup' );

function sitedemo_setup() {

	/**
	 * Sets up Automatic RSS Links in Header *
	 */
	add_theme_support( 'automatic-feed-links' );

	/**
	 * Adds Aside and Gallery Post Formats *
	 */
	add_theme_support( 'post-formats', array( 'aside', 'gallery' ) );

}

This allows your site-plugin to be activated through the plugin menu in WordPress. The ‘add_action’ specifies that the plugin file should be run during the ‘after_setup_theme’ hook – which runs after your theme files have all been loaded. The ‘sitedemo_setup’ is a custom function written to house all of the code you wish to run.

Step 3

Save that file. You can save it as any filename you want, as long as it’s in the plugin folder you just created and ends with a .php extension.

Step 4

Head into your WordPress install and click on the plugins screen. You should see the plugin you just created in the list. Activate it here.

And that’s it. Your site is now running code from the site specific plugin, and you can carry it over from theme to theme