Correctly nest Foreach loop
In the below code there is a nested foreach loop which needs to use the same variables/arguments as the previous foreach loop, however I am misunderstanding how to properly use them together and I have a standalone variable $term which i dont need. If I use the same variables in the nested loop as the first then the code doesnt work correctly.
Correctly being that the the best seller thumbnail for each category is shown. This is working for non-empty categories, however it is also displays a thumbnail for empty categories. It uses the thumbnail from the previous non-empty category, in name order, and I feel this has something to do with the loops.
$max_cat_count = 14;
$qty_per_column = 7;
$args = array(
'taxonomy' => 'product_cat',
'number' => $max_cat_count + 1,
'hide_empty' => 0,
'parent' => 0,
'orderby' => 'name',
'order' => 'ASC',
);
$get_cats = get_terms( $args );
$get_cats = ( ! is_wp_error( $get_cats ) ) ? $get_cats : [];
$default_thumb = content_url( '/uploads/woocommerce-placeholder-416x416.png' );
$total = count( $get_cats );
$list_number = 1;
$_new_col = false;
$columns = '';
foreach ( $get_cats as $i => $cat ) {
if ( $i >= $max_cat_count ) {
break;
}
if ( $i % $qty_per_column === 0 ) {
// Close previous column, if any.
if ( $_new_col ) {
$columns .= '</ul></div><!-- .cat_columns -->';
}
// Open new column.
$id = 'cat-col-' . $list_number;
$columns .= '<div class="menu cat_columns" id="' . $id . '">';
$columns .= '<ul class="hoverimage">';
$_new_col = true;
$list_number++; // increment the columns count
}
if ( $total > $max_cat_count && $i === $max_cat_count - 1 ) {
$columns .= '<li class="all-link"><a href="/all">View All</a></li>';
}
else {
foreach ( $get_cats as $term ) { //$term does nothing
$loop = new WP_Query( [
'post_type' => 'product',
'posts_per_page' => 1,
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num',
//'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $cat->slug, //$cat is variable from first foreach loop
),
),
] );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) {
$loop->the_post();
$thumbnail = $default_thumb;
if ( has_post_thumbnail() ) {
$thumbnail = get_post_thumbnail_id();
$image = $thumbnail ? wp_get_attachment_url( $thumbnail ) : '';
}
}
}
wp_reset_postdata();
}
Leave an answer