0

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 ' ';
    }

2 Answers 2

1

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; 
0
0

Use output buffering to grab the output as a string.

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

return $output;
2
  • nice, but how will be my code? Where i put the rest? Jan 26, 2013 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, 2013 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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