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

The text returned by the_excerpt() does not respect my widget format. I couldn't explain it better so I will just show you my code:

function widget($args, $options) {

    $post_type = $options['post_type'];
    $num_of_posts = $options['limit'];

    // Create a new instance
    $second_query = new WP_Query( array(
                        'post_type' => "$post_type",
                        'posts_per_page' => "$num_of_posts",
                        'post_status' => 'publish',
                    ) ); 

    // The Loop
    if ($second_query->have_posts()) :
      while( $second_query->have_posts() ) : $second_query->the_post();
          $byh_content .= "<p>" . the_excerpt() . "</p>";
      endwhile; else :
          $byh_content = "<p>No " . $options['post_type'] . "s found.</p>";

    $title = "<h3>" . $options['title'] . "</h3>";
    $content = $byh_content;

    echo $before_widget.$title.$content.$after_widget;

The result isn't what I expected. Here's what it looks like when rendered:

widget rendered

The title should be at the top. The reason is that, the excerpt isn't where it is supposed to be:

enter image description here

share|improve this question
up vote 2 down vote accepted

as you are working with strings, you need to use a function which returns the value, instead of echoing it; in this line:

$byh_content .= "<p>" . the_excerpt() . "</p>";

use get_the_excerpt() http://codex.wordpress.org/Function_Reference/get_the_excerpt

share|improve this answer
Whoaah!! Thanks! – Joann Jul 2 '11 at 18:02
Could you please enlighten me why my method isn't working? :-\ – Joann Jul 2 '11 at 18:02
the_excerpt() is echoing (showing) the truncated content immediately where it is used in the code, instead returning it (passing it) to the string variable. there are general (not always) two types of wordpress functions - those starting with the_ that output the results, and the others starting with get_ that return the results. – Michael Jul 2 '11 at 18:13
I see. That was very helpful of you! Thanks! – Joann Jul 2 '11 at 18:18

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.