Include PHP file in Content using [shortcode]

Here is what I have

I am not having any lucking finding how to simply include a file in the content editor using a shortcode.

Read More

For Example if I wanted to include form.php inside my Contact Page how would I make this happen using a shortcode?

Below is was attempting to work with to no avail.

Any help would be appreciated!

// Shortcode implementation
function magic_stuff($atts) {

// turn on output buffering to capture script output

ob_start();

// include file (contents will get saved in output buffer)

include(TEMPLATEPATH.'/wp-content/themes/grainandmortar/inc_static/test.php');

// save and return the content that has been output

$content = ob_get_clean();
return $content;
}
//register the Shortcode handler
add_shortcode('magic', 'magic_stuff');

Related posts

Leave a Reply

5 comments

  1. I modified some code from an old blog post to do this, and allow for query-strings to be attached to the file as well.

    Original credit goes to amberpanther.com, and it turns out they made a plug-in out of this, too.

    //create the shortcode [include] that accepts a filepath and query string
    //this function was modified from a post on www.amberpanther.com you can find it at the link below:
    //http://www.amberpanther.com/knowledge-base/using-the-wordpress-shortcode-api-to-include-an-external-file-in-the-post-content/
    //BEGIN amberpanther.com code
    function include_file($atts) {
         //if filepath was specified
         extract(
              shortcode_atts(
                   array(
                        'filepath' => 'NULL'
                   ), $atts
              )
         );
    
         //BEGIN modified portion of code to accept query strings
         //check for query string of variables after file path
         if(strpos($filepath,"?")) {
              $query_string_pos = strpos($filepath,"?");
              //create global variable for query string so we can access it in our included files if we need it
              //also parse it out from the clean file name which we will store in a new variable for including
              global $query_string;
              $query_string = substr($filepath,$query_string_pos + 1);
              $clean_file_path = substr($filepath,0,$query_string_pos);     
              //if there isn't a query string
         } else {
              $clean_file_path = $filepath;
         }
         //END modified portion of code
    
         //check if the filepath was specified and if the file exists
         if ($filepath != 'NULL' && file_exists(get_stylesheet_directory_uri() . "/" . $clean_file_path)){
              //turn on output buffering to capture script output
              ob_start();
              //include the specified file
              include(TEMPLATEPATH.$clean_file_path);
              //assign the file output to $content variable and clean buffer
              $content = ob_get_clean();
              //return the $content
              //return is important for the output to appear at the correct position
              //in the content
              return $content;
         }
    }
    //register the Shortcode handler
    add_shortcode('include', 'include_file');
    //END amberpanther.com code
    //shortcode with sample query string:
    //[include filepath="/get-posts.php?format=grid&taxonomy=testing&term=stuff&posttype=work"]
    

    I set mine to pull from the stylesheet uri (so it will work with child themes and such), but you could adjust that code easily to pull from anywhere (including plug-in directories), or remove it altogether and just use the full path when including the file. You could even add a conditional with a trigger character at the beginning that tells it to use a specific path based on what the first character of the file name is, like using a “#” for the template directory, etc.

    I use it to pull in a file called get-posts.php that lives in my template directory and formats the output of various posts based on a series of parameters provided in the query string. It saves me from needing special templates because I can include the file, send it a format and it will output the posts with the markup I’ve specified in the get-posts.php file.

    It also allows clients to pull custom post types into actual blog-posts in specific formats and is quite handy.

    Let me know if you need clarification on anything.

  2. Here’s another way to do it, utilizing get_template_part of wordpress

    function include_file($atts) {
         $a = shortcode_atts( array(
            'slug' => 'NULL',
           ), $atts );
    
          if($a['slug'] != 'NULL'){
            ob_start();
            get_template_part($a['slug']);
            return ob_get_clean();
          }
     }
     add_shortcode('include', 'include_file');
    

    examples:

    [include slug="form"]

    [include slug="sub-folder/filename_without_extension"]

  3. There is an error in the solution provided by @adedoy, since $slug is never defined. This worked for me:

    function include_file($atts) {
    
    $atts = shortcode_atts(
        array(
        'path' => 'NULL',
        ), $atts, 'include' );
    
        ob_start();
        get_template_part($atts['path']);
        return ob_get_clean();
    
    }
    
    add_shortcode('include', 'include_file');
    

    Usage: [include path=”path/from/root”]

  4. Ok, first I’d ditch the output buffering.

    Second change:

    include(TEMPLATEPATH.'/wp-content/themes/grainandmortar/inc_static/test.php');
    

    To

    include( get_stylesheet_directory() . '/inc_static/test.php');
    

    Finally,

    Reading the documentation here: https://codex.wordpress.org/Shortcode_API

    You need to return something, if your test.php doesn’t output something in a returnable fashion, you’re going to have a bad time.

    So make sure that test.php does something along the lines of:

    $output = "STUFF"; // a variable you could return after include.
    // or
    function test() {
        // do stuff
        return $stuff; // a function that returns a value that you can call after include.
    }
    

    Then after you include your test.php file — you just return $output or do something like return test();.

  5. I found that the include code originally written by the AmberPanther folks didn’t work so well for me, so I found another wordpress plugin that does pretty much the same thing. It’s called Include Me, by Stefano Lissa. The usage is pretty much that you write your path to the file, starting from the root directory of your site.

    So for example, within your WordPress page you’d write:

    [includeme file="wp-content/themes/your-theme/code/example-code.php"]
    

    and within your functions.php file you’d include:

    <?php
    
    if (is_admin()) {
    include dirname(__FILE__) . '/admin.php';
    
    } else {
    
    function includeme_call($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('&amp;', '&', $value);
                if ($key == 'src') {
                    $value = strip_tags($value);
                }
                $tmp .= ' ' . $key . '="' . $value . '"';
            }
            $buffer = '<iframe' . $tmp . '></iframe>';
        }
        return $buffer;
    }
    
    // Here because the funciton MUST be define before the "add_shortcode" since 
    // "add_shortcode" check the function name with "is_callable".
    add_shortcode('includeme', 'includeme_call');
    }
    

    of course, I’d also recommend just installing the plugin so you can take advantage of updates. https://wordpress.org/plugins/include-me/