11 Aug 2017

Displaying a specific pages content outside the loop

This is a super handy snippet that will display a specific pages content. It's very usefull to display content in a module or widget area outside of the main content area.

To display the content, use the following PHP snippets but remember to replace the ID for the page. Insert the following into the position of the theme that you intend displaying the content at:

// Outputs the content from the wysiwyg. Removes the HTML formatting.
        $post   = get_post( 1832 );
        echo apply_filters(‘the_content’, $post->post_content);
// Outputs the content from the wysiwyg. Maintains the HTML formatting.
        $post_1832 = get_post( 1832, ARRAY_A );
        $output =  apply_filters( 'the_content', $post->post_content );
        echo $output;
// Displays specific objects (Such as the page title in this example)
$post_1832 = get_post( 1832, ARRAY_A );
$title = $post_1832['post_title'];
echo $title;

For reference, WP_Post OBJECT contains following fields:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
WP_Post Object
(
    [ID] =>
    [post_author] =>
    [post_date] =>
    [post_date_gmt] =>
    [post_content] =>
    [post_title] =>
    [post_excerpt] =>
    [post_status] =>
    [comment_status] =>
    [ping_status] =>
    [post_password] =>
    [post_name] =>
    [to_ping] =>
    [pinged] =>
    [post_modified] =>
    [post_modified_gmt] =>
    [post_content_filtered] =>
    [post_parent] =>
    [guid] =>
    [menu_order] =>
    [post_type] =>
    [post_mime_type] =>
    [comment_count] =>
    [filter] =>
)

 

More information at the codex

 

EDIT:
I've had some problems maintaining the markup whilst displaying teh page content using the method above. I've since discovered the following get the same result:

// Outputs the content from the wysiwyg. Removes the HTML formatting.
    $my_postid = 6101;//This is page id or post id
            $content_post = get_post($my_postid);
            $content = $content_post->post_content;
            $content = apply_filters('the_content', $content);
            $content = str_replace(']]>', ']]>', $content);
            echo $content;