下面的代码在悬停时显示产品类别名称、链接及其缩略图。检索到的缩略图($图像)是通过woocommerce产品类别菜单手动设置的缩略图。
相反,我试图从每种产品中最畅销的产品中获取这些产品类别缩略图。我真的不知道如何包含新的wp\\u查询(&U);获取此的\\u post\\u meta。加上这个,我的缩略图就不再显示了。
$max_cat_count = 24;
$qty_per_column = 6;
$args = array(
\'taxonomy\' => \'product_cat\',
\'number\' => $max_cat_count + 1, // keep the + 1
\'hide_empty\' => 0,
);
$get_cats = get_terms( $args );
$get_cats = ( ! is_wp_error( $get_cats ) ) ? $get_cats : [];
$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 ) {
if ( $_new_col ) {
$columns .= \'</ul></div><!-- .cat_columns -->\';
}
$id = \'cat-col-\' . $list_number;
$columns .= \'<div class="menu cat_columns" id="\' . $id . \'">\';
$columns .= \'<ul class="hoverimage">\';
$_new_col = true;
$list_number++;
}
if ( $total > $max_cat_count && $i === $max_cat_count - 1 ) {
$columns .= \'<li class="all-link"><a href="/view-all">View All </a></li>\';
} else {
$terms = get_terms( \'product_cat\', array(
\'hide_empty\' => false,
) );
foreach ( $terms as $term ) {
$query = new WP_Query( [
\'post_type\' => \'product\',
\'posts_per_page\' => 1,
\'meta_key\' => \'total_sales\',
\'orderby\' => \'meta_value_num\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'slug\',
\'terms\' => $term->slug,
),
),
] );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$thumbnail = content_url( \'/uploads/woocommerce-placeholder-416x416.png\' );
if ( has_post_thumbnail() ) {
$thumbnail = get_post_thumbnail_id();
$image = $thumbnail ? wp_get_attachment_url( $thumbnail ) : \'\';
}
}
}
wp_reset_postdata();
}
$link = \'<a href="\' . esc_url( get_term_link( $cat ) ) . \'">\' . esc_html( $cat->name ) . \'</a>\';
$columns .= \'<li class="menu-item" data-image="\' . esc_url( $image ) . \'">\' . $link . \'</li>\';
}
}
// Close last column, if any.
if ( $_new_col ) {
$columns .= \'</ul></div><!-- .cat_columns -->\';
}
?>
最合适的回答,由SO网友:Ahmad Wael 整理而成
我从您的问题中了解到的是,您希望获得每个类别中最畅销的产品,并将其图像设置为类别拇指。
您需要遍历所有类别,然后还需要在每个类别中为当前类别循环中的最佳产品创建一个嵌套循环,然后才能访问畅销产品图像。
以下代码将描述更多内容(未测试):
$terms = get_terms( \'product_cat\', array(
\'hide_empty\' => false,
) );
foreach ( $terms as $term ) {
$query = new WP_Query( [
\'post_type\' => \'product\',
\'posts_per_page\' => 1,
\'meta_key\' => \'total_sales\',
\'orderby\' => \'meta_value_num\',
\'tax_query\' => array(
array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'slug\',
\'terms\' => $term->slug,
),
),
] );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$thumbnail = \'DEFAULT THUMBNAIL ID\';
if ( has_post_thumbnail() ) {
$thumbnail = get_post_thumbnail_id();
//THEN YOU WILL BE ABLE TO SET THE CATEGORY THUMBNAIL WITH THIS PRODUCT THUMBNAIL ID
}
}
}
wp_reset_postdata();
}