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.

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

<?php 
    $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> 
      </div>
<?php endforeach; ?> 

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

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

            ), $atts));

            return ' ';
    }
share|improve this question

2 Answers 2

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>';
endforeach; 
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.

ob_start();
// 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

 
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.