We love WordPress shortcodes! They are powerful, flexible and easy way for developers to add functionality and features to WordPress posts.

So you might have arrived here because you are wondering, “How can I include PHP scripts in posts and pages?”. Today we are going to show you how to create a shortcode that will allow you to use PHP includes within the content editor in WordPress.

Add the following to your theme’s functions.php file:

if (is_admin()) {
include dirname(__FILE__) . '/admin.php';

} else {

function include_shortcode_function($attrs, $content = null) {

    if (isset($attrs['file'])) {
        $file = strip_tags($attrs['file']);
        if ($file[0] != '/')
            $file = ABSPATH . $file;

        ob_start();
        include($file);
        $buffer = ob_get_clean();
        $options = get_option('includeme', array());
        if (isset($options['shortcode'])) {
            $buffer = do_shortcode($buffer);
        }
    } else {
        $tmp = '';
        foreach ($attrs as $key => $value) {
            if ($key == 'src') {
                $value = strip_tags($value);
            }
            $value = str_replace('&', '&', $value);
            if ($key == 'src') {
                $value = strip_tags($value);
            }
            $tmp .= ' ' . $key . '="' . $value . '"';
        }
        $buffer = '<iframe' . $tmp . '></iframe>';
    }
    return $buffer;
}

add_shortcode('include', 'include_shortcode_function');
}

And here’s the shortcode:

[include file="wp-content/themes/theme-name/includes/example-include.php"]

Using A Plugin

This can also be achieved using a plugin, a great one we have previously tested is Include Me.

Plugin Description

Include Me helps to include in posts or pages external files usually to be shared between different posts or pages or that contains PHP or other code that can be compromised by the visual editor.

Free Graphics, Icons, Tutorials
Free Graphics Free Christmas Vector Icon Graphics Pack 2017Free Fitness Vector Icons Graphics PackFree Camping Vector Graphics PackFree Summer Graphics PackFree File Icon PackFree Fast Food Vector Graphics
Sharing is caring...
Like & Follow
Share the love, share this page! Facebook Twitter Digg Reddit LinkedIn Pinterest Email
Close [X]
The Web Taylor
1000 Lakeside North Harbour Portsmouth, Hampshire PO6 3EN
02392 123358