Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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!

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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; 
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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