Shortcode of a function

时间:2013-01-26 作者:Lucas Fernandes

我得到了这个函数,我想将“foreach”的contents divs作为return。我该怎么做?

<?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 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成

构建字符串,而不是直接输出内容。

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

SO网友:webaware

使用output buffering 以字符串形式获取输出。

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

return $output;

结束

相关推荐

Fix html inside a for loop

我想为第二个链接获得正确的链接格式,我尝试了很多次移动a open标记,但结果不可能如下图所示。foreach( $terms as $term ) : echo \'<div class=\"one_half last\">\'; $customposts = new WP_Query( \"taxonomy=$taxonomy&term=$term->slug&posts_per_page=2\" ); &