简体   繁体   中英

Wordpress - wp_query inside of a foreach loop

I am using ACF to build a product catalogue. I need to create a list like that:

+Category name
-list
-of
-products
-in
-that
-category
+Another category name
-list
-of
-...
-in the matching category
For all of the categories.

Categories names are the terms of the 'product_categories' taxonomy. The products belong to a custom post type 'products'.

I've already build a loop that displays links to all of the categories with names and images:

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

It works fine.
Then I rebuilded it to display the thing i want:

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

It almost works. The problem is that it displays all of the product names BUT only for the first category, after all of the products from the first category in loop are echoed, following categories are empty (just the category names, no matching items).
How can I make it display products in all of the categories, not just the first one? And what's wrong with the code?

Have you tried adding wp_reset_query(); before the end of the foreach loop?

More info http://codex.wordpress.org/Function_Reference/wp_reset_query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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