Zend certified PHP/Magento developer

How to Develop a PHP File Include Plugin for WordPress

WordPress can save developers weeks of effort. It’s difficult to justify writing your own CMS when it offers so many features. That said, there are times when you want to inject your own PHP code; perhaps a custom form or a report generated by another system.

To insert your code on every WordPress page or post, you can simply add a PHP include() function to page.php or single.php accordingly, e.g.


include('mycode.php');

Assuming mycode.php resides in your theme folder (wp-content/themes/theme-name), it will be included and executed at that point.

But what if you need to include a file on a specific post/page or within the middle of a content block? We need a WordPress plugin…

Creating the Plugin

Create a new file named php-include.php in your plugins folder (wp-content/plugins) and add a header so it can be identified by WordPress:


?php
/*
Plugin Name: PHP File Includer
Plugin URI: http://www.sitepoint.com/
Description: Include PHP files using a shortcode
Version: 1.0
Author: Craig Buckler
Author URI: http://optimalworks.net/
License: Use this how you like!
*/

This is followed by our primary function, PHP_Include(). It expects an array of parameters although we’re just using one — file. If it’s not passed, file set to ‘default’:


// include PHP file
function PHP_Include($params = array()) {
	extract(shortcode_atts(array(
	    'file' = 'default'
	), $params));
	ob_start();
	include(get_theme_root() . '/' . get_template() . "/$file.php");
	return ob_get_clean();
}

The function assumes you’re requesting a file which resides in the theme folder. The last three lines include the file and return its executed contents using PHP’s output buffering functions.

…comes great responsibility. This plugin may be small but it allows anyone to execute arbitrary code. That’s not be a problem if you’re the sole editor of your own blog, but you should be wary of other users.

Optionally, you could modify the include statement’s location or only permit files with a specific name pattern, e.g. “/include/mycode-$file.php”. This should safeguard against users including any PHP file.

Finally, we’ll register our function as a shortcode handler:


// register shortcode
add_shortcode('phpinclude', 'PHP_Include');

Save the file and activate the plugin in your WordPress control panel.

Including a PHP File

The following shortcode can now be added to any page or post:


[phpinclude file='mycode']

Assuming mycode.php exists in your theme’s folder, it will be inserted at that point in the content.

I hope you find it useful.

Written By: