如何用逗号列出我的所有帖子(但不要在最后一篇帖子之后)。。。
<?php
// WP_Query arguments
$args = array(
\'post_type\' => array( \'post\' ),
\'tax_query\' => array(
array (
\'taxonomy\' => \'day_time\',
\'field\' => \'slug\',
\'terms\' => \'mon-night\')),
\'post_status\' => array( \'publish\' ),
\'nopaging\' => false,
\'posts_per_page\' => \'20\',
\'ignore_sticky_posts\' => true,
\'order\' => \'DESC\',
\'separater\' => \', \',
\'orderby\' => \'modified\',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<?php the_title(); ?>
<?php }
} else { ?>
<?php }
// Restore original Post Data
wp_reset_postdata();
?>
<?php } else { ?>
<?php } ?>
最合适的回答,由SO网友:WebElaine 整理而成
不要立即输出所有内容,而是将其保存到变量中,以便可以有条件地在项目之间添加逗号(可能还有空格):
<?php
// The Loop
if ( $query->have_posts() ) {
// Save the number of posts found
global $wp_query;
$total_posts = $wp_query->post_count;
// Set a counter variable
$i=0;
while ( $query->have_posts() ) {
$query->the_post();
// Save the title to a variable instead of outputting
$output .= get_the_title();
// Increment the counter each time
$i++;
}
// Outside the loop, since you only want 1 comma each time
if($i != $total_posts) {
// Add a comma and a space
$output .= \', \';
}
// Last but not least, display the output
echo $output;
}
?>