Use the_content outside the loop

The question:

I was trying to get first 100 words of the content in the header, and I use the following snippet to get the first 100 words in the loop, but is it possible to get the value outside the loop:

$cstring = get_the_content( '' );
$newcString = substr( $cstring, 0, 100 );
echo'<p>' . $newcString . '</p>';

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

If you are trying to do it for the current page you are on you can just use this:

global $post;
$content = $post->post_content;`

This will get the content for the current post instead of having to set the ID specifically.

Method 2

I wrote an article on this here, but here’s a summary of the points:

  • the_content can only be used ‘inside the loop’
  • ‘inside the loop’ can only be correctly ‘simulated’ by calling setup_postdata() and global $post.
  • You then need to clear up after yourself by calling wp_reset_postdata()

The below code provides a function to retrieve post content from the post ID. It differs from @NickYoung answer in that the content you receive is not what’s stored in the post_content column of the posts table, but rather that content after it’s been through the_content filter (e.g. shortcodes parsed etc).

The code

/**
 * Display the post content. Optinally allows post ID to be passed
 * @uses the_content()
 * @link http://stephenharris.info/get-post-content-by-id/
 * @link https://wordpress.stackexchange.com/questions/142957/use-the-content-outside-the-loop
 * @param int $id Optional. Post ID.
 * @param string $more_link_text Optional. Content for when there is more text.
 * @param bool $stripteaser Optional. Strip teaser content before the more text. Default is false.
 */
function sh_the_content_by_id( $post_id=0, $more_link_text = null, $stripteaser = false ){
    global $post;
    $post = get_post($post_id);
    setup_postdata( $post, $more_link_text, $stripteaser );
    the_content();
    wp_reset_postdata( $post );
}

Method 3

You can use get_page() or get_post() to get content out side the loop

//For page
$page_id = 1;
$get_page_object = get_page( $page_id );
$page_object = $get_page_object->post_content;
echo $newpagecString = substr($page_object, 0, 100);
//For post
$post_id = 2;
$get_post_object = get_post( $post_id );
$post_object = $get_post_object->post_content;
echo $newpostcString = substr($post_object, 0, 100);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment