0

My code takes the first sentence of a post and places it's content inside a variable. The problem is it works only inside the loop.

I need help making this code outside the loop, becouse I want to use the posts first sentace as description in the header.php

Here it is:

<? ob_start();
the_content();
$old_content = ob_get_clean();
$content = strip_tags($old_content);
$match = null;
preg_match('/(.*?[?\.!]{1,3})/', $content, $match);  
$first_sentence = $match[1];   
$the_rest = substr($content, strlen($first_sentence)); 
if ( $first_sentence != '' && $the_rest != '' ){
   echo '<h2>'.$first_sentence.'</h2>';
   echo '<p>'.$the_rest.'</p>';
} ?>

One more thing, it would be perfect to keep the posts formating in this code. Any ideea how I can do that?

Ty very much, take care!

1 Answer 1

0

To get post info outside the regular loop, you can use WP Query Reference

In your example you can try something like;

$firstsentance = new WP_Query();
$firstsentance->query('posts_per_page=-1');  // add additional  query parameters as needed, this will query all posts
$old_content = the_content()';

//do your php stuff here

endwhile; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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