WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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();
$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
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

share|improve this answer

Your Answer


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.