WordPress: Including a Page or Post within another Page or Post

wordpress-logo-notext-rgb

As CEO of a start-up, I have the privilege of wearing a whole lot of hats. One of them is for the Web Developer. Within our WordPress site I have a situation where I want to display show specification content on both The 5 Dragon Daughter’s show page and also on the Booking page. Now, I could copy and paste, but if I make updates to that information I don’t want to have to change it in two places. I may forget that I have it in both spots and have information that is out of date on our website.

To solve this I went looking for how to include the contents of one page in another page. There was nothing available that I could simply plop into WordPress, but I did find this blog entry on how to Create Your Own WordPress Plugin.  The include functionality I wanted to add to WordPress is something that is ideal for a plugin rather than the functions.php as I might want it available across multiple themes.

Using info from that plugin tutorial and the modifying code from another blog article by the same author, I constructed code (appended at the end of this post) that enables me to include a page or post within another post in WordPress.  After setting up the proper directly structure and php files, I went to the Dashboard, activated my plugin, and now I’m good to go. I can include contents of pages or posts within other pages/posts by using the following syntax:

So, the show specs sections on The 5 Dragon Daughter Page and the Book a Show page are both coming from a third page which contains only the show specs.

 
<?php /*
 * Plugin Name: Include Plugin for WordPress
 * Plugin URI: http://www.seriouslyproductions.com/
 * Description: Displays the content of a page/post within a different page/post.
 * Author: David Wolff
 * Author URL: http://www.seriouslyproductions.com/about-us/dave-wolff/
 * Version: 1.0
 * License: GPL2
 */
function seriously_include ($atts) { 
    //If the id value isn't numeric then return nothing
    //to prevent any strange and unwanted behavior.
    if (!is_numeric($atts[id])) {
    	return '';
    }

    $includeId = intval($atts[id]); 
    $output = ''; 
    // Look for pages with the ID. 
    query_posts("page_id=$includeId"); 
    if (have_posts()) { 
        while (have_posts()) { 
            the_post(); 
            $output .= get_the_content($post->ID); 
        } 
    } else { 
        //The ID wasn't for a page, try a post. 
        query_posts("p=$includeId"); 
        while (have_posts()) { the_post(); 
            $output .= get_the_content($post->ID); 
        } 
    } wp_reset_query(); 
    return $output; 
} 

add_shortcode("sp_include", "seriously_include"); ?> 

Leave a Reply