Making a Site Specific WordPress Plugin

Often we need certain functions to exist, or the site to behave a certain way.  Rather than adding code to the theme’s functions.php file, we create a site specific plugin.

Here is my template for this.  As an example, I will use my  “wplab” playground site.  We create a folder <mysite>-site-plugin.  We created the wplab-site-plugin folder. In this folder we create the standard “empty” index.php file, and the actual plugin file which I call plugin.php.

<?php
// Silence is golden.
<?php
/*
Plugin Name: Site Plugin for wplab.drmagu
Description: Site specific code changes for wplab.drmagu
*/
namespace drmagu\siteplugin;
/* only allow WP environment */
defined('ABSPATH') or die("Oops.  Not here buddy!");

/* Start Adding Functions Below this Line */

/* Stop Adding Functions Below this Line */

First, notice that we use a namespace to avoid stepping on WordPress, Theme or other Plugin functions.  Also, we ensure the plugin code will only if called from the WordPress environment.

wplab site plugin

To complete the example, we will use this plugin to disable xml_rpc for the site, and to allow the execution of PHP code in text widgets.  And since I was experimenting with PHP sessions, I added a shortcode to display the global PHP sessions data.  Here is the fleshed out plugin.php file.

<?php
/*
Plugin Name: Site Plugin for wplab.drmagu
Description: Site specific code changes for wplab.drmagu
*/
namespace drmagu\siteplugin;
/* only allow WP environment */
defined('ABSPATH') or die("Oops.  Not here buddy!");

/* Start Adding Functions Below this Line */

/* disable xmlrpc */
add_filter('xmlrpc_enabled', '__return_false');

/* allow PHP in the text widget */
add_filter('widget_text','drmagu\siteplugin\execute_php',100);
function execute_php($html){
	if(strpos($html,"<"."?php")!==false){
	  ob_start();
	  eval("?".">".$html);
	  $html=ob_get_contents();
	  ob_end_clean();
	}
	return $html;
}

/* shortcode to show the PHP Sessions data */
add_shortcode('drmagu_show_session_data', 'drmagu\siteplugin\show_session');
function show_session() {
	$output = "";
	$output .= "<pre>Session data: \n";
	$output .= print_r($_SESSION, true);
	$output .= "</pre>";
	$output .= "<pre>Cookie data: \n";
	$output .= print_r($_COOKIE, true);
	$output .= "</pre>";
	return $output;
}

/* Stop Adding Functions Below this Line */

This is a great way to customize a site and to experiment without having to edit functions.php in a theme or develop a full-blown plugin.

Leave a Reply

You must be logged in to post a comment.