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

I got this function and i want to make the contents divs of "foreach" as return. How can i do that?

    $args = array( 'numberposts' => 6, 'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
    $postslist = get_posts( $args );

    foreach ($postslist as $post) : setup_postdata($post); ?>
       <div class="events">
             <p><strong><?php the_date(); ?></strong></p>
           <p><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></p> 
<?php endforeach; ?> 

/// Top Section Block
add_shortcode('top_section_block', 'shortcode_top_section_block');

    function shortcode_top_section_block($atts) {
                'content' => '',

            ), $atts));

            return ' ';
share|improve this question
up vote 1 down vote accepted

Build a string instead of directly outputting the contents.

$str = '';
foreach ($postslist as $post) : setup_postdata($post); 
  $str .= '<div class="events">';
    $str .= '<p><strong>'.get_the_date().'</strong></p>';
    $str .= '<p><a href="'.get_permalink().'" title="'.esc_attr(get_the_title()).'">'.get_the_title().'</a></p>';
  $str .= '</div>';
share|improve this answer
Thanks bro, worked fine! – Chead Jan 28 '13 at 13:54

Use output buffering to grab the output as a string.

// do your foreach bits here
$output = ob_get_clean();

return $output;
share|improve this answer
nice, but how will be my code? Where i put the rest? – Chead Jan 26 '13 at 13:56
My code goes in your shortcode function. See the bit that says, // do your foreach bits here ? That's where your foreach code goes. – webaware Jan 26 '13 at 14:06
Thanks bro! Worked fine too! – Chead Jan 28 '13 at 14:53

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.