我的类别来自逗号分隔的位置,然后我将其放入get\\u posts的args数组中,但我的查询只提供最后一个类别的帖子。请查看下面我的代码:
$content_arr = explode(",", $content);
if ( is_array($content_arr) && count($content_arr) > 0 ) {
foreach ($content_arr as $category_name) { // Category loop
$args = array(
\'category_name\' => trim($category_name),
\'posts_per_page\' => 7,
\'order\' => \'DESC\',
\'orderby\' => \'post_date\',
);
$output = \'\';
// $posts = get_posts($args);
$post_counter = 1;
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
if ( has_post_thumbnail() ):
//the_post_thumbnail();
else:
endif;
$output .= \'<div class="col-md-4 mb-5">\'.get_the_ID().\'-\'.get_the_title().\'</div>\';
$post_counter++;
endwhile;
$the_query->reset_postdata();
echo $post_counter."-";
endif;
在$content\\u arr中,有3个类别作为数组元素,因此first foreach运行了3次,但我的输出仅显示一个类别的帖子。不知何故,它正在重置我以前分类的结果。如何逐个显示我的所有类别帖子?谢谢
SO网友:Jacob Peattie
问题是,在每个循环的开头,您都会重置$output
到空字符串:
$output = \'\';
所以当then循环完成时,
$output
将仅包含最后一个循环的输出。
要解决此问题,只需将此行移出循环,初始化变量,同时只需使用.=
回路内部:
$content_arr = explode( \',\', $content);
$output = \'\';
if ( is_array( $content_arr ) && count( $content_arr ) > 0 ) {
foreach ( $content_arr as $category_name ) {
$args = array(
\'category_name\' => trim( $category_name ),
\'posts_per_page\' => 7,
\'order\' => \'DESC\',
\'orderby\' => \'post_date\',
);
$post_counter = 1;
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
if ( has_post_thumbnail() ):
//the_post_thumbnail();
else:
endif;
$output .= \'<div class="col-md-4 mb-5">\' . get_the_ID() . \'-\' . get_the_title() . \'</div>\';
$post_counter++;
endwhile;
$the_query->reset_postdata();
echo $post_counter . "-";
endif;