我正在尝试自定义我的WooCommerce产品商店存档页面,以首先显示被标记为收藏的所有产品,然后显示所选类别中的所有其他产品。
我已经尝试过将以下循环放入我的archive-product.php文件中,但是有两个问题:
如果我位于/product-category/toys/
存档页面上,它将显示所有类别的产品。只能显示特定类别的产品(例如玩具)。
每个分页页面首先显示特色产品,然后显示常规产品。实际上,仅应该在第一页上显示特色产品,并且一旦显示所有特色产品,便应显示常规产品。似乎每个页面都显示两个单独的循环,而不是一个循环。
ALSO,这是执行此操作的首选方法,还是我应该使用pre_get_posts
?
<?php woocommerce_product_loop_start(); ?>
<?php
//CUSTOM LOOP
// Display featured Products first.
$query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1 ,
'tax_query' => array( array(
'taxonomy' => 'product_visibility',
'field' => 'term_id',
'terms' => 'featured',
'operator' => 'IN',
) )
) );
$featured_product_names = array();
$featured_product_id = array();
if ( $query->have_posts() ): while ( $query->have_posts() ): $query->the_post();
$product = wc_get_product( $query->post->ID );
wc_get_template_part( 'content', 'product' );
endwhile; wp_reset_query();endif;
// fetch other product which is not featured
$my_query = new WP_Query(array(
'post__not_in' => $featured_product_id,
'post_type' => 'product'
));
if ( $my_query->have_posts() ): while ( $my_query->have_posts() ): $my_query->the_post();
$product = wc_get_product( $query->post->ID );
wc_get_template_part( 'content', 'product' );
endwhile; wp_reset_query();endif;
?>
<?php woocommerce_product_loop_end(); ?>
我认为我走在正确的道路上,但无法指出问题所在。
感谢所有帮助!
答案 0 :(得分:0)
您已将$featured_product_id
定义为数组,但未在其中添加postid来跳过其他循环。请检查以下代码,它将起作用。
<?php woocommerce_product_loop_start(); ?>
<?php
//CUSTOM LOOP
// Display featured Products first.
$query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1 ,
'tax_query' => array( array(
'taxonomy' => 'product_visibility',
'field' => 'term_id',
'terms' => 'featured',
'operator' => 'IN',
) )
) );
$featured_product_names = array();
$featured_product_id = array();
if ( $query->have_posts() ): while ( $query->have_posts() ): $query->the_post();
$featured_product_id[] = get_the_ID();
$product = wc_get_product( $query->post->ID );
wc_get_template_part( 'content', 'product' );
endwhile; wp_reset_query();endif;
// fetch other product which is not featured
$my_query = new WP_Query(array(
'post__not_in' => $featured_product_id,
'post_type' => 'product'
));
if ( $my_query->have_posts() ): while ( $my_query->have_posts() ): $my_query->the_post();
$product = wc_get_product( $query->post->ID );
wc_get_template_part( 'content', 'product' );
endwhile; wp_reset_query();endif;
?>
<?php woocommerce_product_loop_end(); ?>