繁体   English   中英

Wordpress-foreach循环内的wp_query

[英]Wordpress - wp_query inside of a foreach loop

我正在使用ACF建立产品目录。 我需要创建一个这样的列表:

+类别名称
-list
-的
- 产品
-在
-那
-类别
+另一个类别名称
-list
-的
-...
-在匹配类别中
对于所有类别。

类别名称是“ product_categories”分类法的术语。 产品属于自定义帖子类型“产品”。

我已经建立了一个循环,该循环显示具有名称和图像的所有类别的链接:

$terms = get_terms("product_categories", array('hide_empty' => false));
            if ( !empty( $terms ) && !is_wp_error( $terms ) ){
                foreach ( $terms as $term ) {
                    echo '<a href="'.get_term_link($term).'">';
                    echo '<p>'.$term->name.'</p>';
                    echo '<img src="'.get_field('image-field-name', $term).'"></a></div>';
                }
            }

工作正常。
然后我重建它以显示我想要的东西:

$terms = get_terms("product_categories", array('hide_empty' => false));
            if ( !empty( $terms ) && !is_wp_error( $terms ) ){
                foreach ( $terms as $term ) {
                    $category= $term->name;
                    echo '<p>'.$category.':</p>';
                    product_list($category);
                    echo '<br/><br/>';
                }
            }

function product_list($category_name){
$inner_args=array(
'post_type' => 'products',
'product_categories' => $category_name
);
$my_query = null;
$my_query = new WP_Query($inner_args);
if( $my_query->have_posts() ) {
  while ($my_query->have_posts()) : $my_query->the_post(); ?>
    <?php echo '<br/>Product: '.get_field('name_of_the_product');
    ?>
    <?php
  endwhile;
}
}

它几乎可以工作。 问题在于,在回显循环中来自第一个类别的所有产品之后,它仅显示第一个类别的所有产品名称,但以下类别为空(只是类别名称,没有匹配项)。
如何使它显示所有类别的产品,而不仅仅是第一个? 代码有什么问题?

您是否尝试过添加wp_reset_query(); 在foreach循环结束之前?

更多信息http://codex.wordpress.org/Function_Reference/wp_reset_query

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM