下面的代码旨在简单地循环浏览帖子,给它们添加html格式的机会,然后将它们返回到短代码位置。我有条件逻辑,它根据传入的“类别”(术语)定义格式。我需要在同一页上输出两次,但我只看到在循环之外添加的代码。
add_shortcode(\'my_shortcode\',\'generate_my_shortcode_content\');
function generate_my_shortcode_content($atts){
$a = shortcode_atts( array(
\'post-count\' => 3,
\'category\' => \'default-cat\'
), $atts );
$post_count = (int)$a[\'post-count\'];
$post_category = explode(\',\', $a[\'category\']);
$args = array(
\'post_type\' => \'my-type\',
\'posts_per_page\' => $post_count,
\'tax_query\' => array(
array(
\'taxonomy\' => \'my-taxonomy\',
\'field\' => \'slug\',
\'terms\' => $post_category
)
)
);
$test = "<h1>";
$query = new WP_Query( $args );
if($query->have_posts()):while($query->have_posts()):$query->the_post();
$post_id = get_the_ID();
$post_title = get_the_title($post_id);
$post_content = get_the_content($post_id);
$posts .= $post_id . $post_title . $post_content;
$test .= "this is a test";
endwhile;wp_reset_postdata();endif;
$test .= "</h1>";
return $posts . $test;
}
此函数将返回
{Post ID}{Post Title}{Post Content}<h1>this is a test</h1>
第一次执行时,但只会返回
<h1></h1>
在第二个。为什么会这样?