Use the_content outside the loop

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>';

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x