0

I've created a page template and used this code to call a post which contains a shortcode:

$post_id = 129;
if( get_post_status( $post_id ) == 'publish' ) {
    the_content();
}

The problem is that this code works fine in the index.php but not in my page template. Why is that?

Help please.

1

The reason your post is not displaying properly is because functions such as the_title(), the_permalink(), and the_content() ( called Template Tags ) can only be used whenever inside "The Loop" or whenever set up properly. There are two options to display your content properly:

Functions: get_post(), setup_postdata() and wp_reset_postdata()

First you would need to get the WP_Post Object and pass it into the setup_postdata() function so that WordPress can setup the template tags to pull in the correct content. Finally, we would need to reset the global $post object by calling wp_reset_postdata().

global $post;               //  Get the current WP_Post object.

$post = get_post( 129 );    // Get our Post Object.
setup_postdata( $post );    // Setup our template tags.

if( 'publish' == $post->post_status ) {
    the_content();
}

wp_rest_postdata();         // Reset the global WP_Post object.

Tad Easier using apply_filters()

This is a little more straight-forward and doesn't require so much code which is nice. You won't have access to Template Tags like you would in the above example but if you're just displaying the post content and processing their shortcodes you won't need Template Tags.

$post_id = 129;

if( 'publish' == get_post_status( $post_id ) ) {
    $post_content = get_post_field( 'post_content', $post_id );
    echo apply_filters( 'the_content', $post_content );
}

The above grabs the content from the database then runs it through a WordPress filter which processes the_content() hook to give us our desired output, shortcodes processed and all.

  • Thanx sir, i'll try your solution. – hazam120 Nov 24 '16 at 9:41
0

You can use get_post() function to get the post content by post id.

$post_id = 129;
if( get_post_status( $post_id ) == 'publish' ) {

    $post_content = get_post($post_id);
    $content = $post_content->post_content;
    echo apply_filters('the_content',$content);
}
  • Do note though, this will not process any shortcodes but just display them in plain text. – Howdy_McGee Nov 23 '16 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.