我想在 WooCommerce 的默认商店页面中仅显示特色产品,仅此而已... 有没有办法在 WooCommerce 商店模板中仅显示特色产品?
您应该使用挂钩在
woocommerce_product_query_tax_query
过滤器挂钩中的自定义功能,该功能将仅显示商店中的特色产品(而不是其他档案页面):
// Display featured products in shop pages
add_filter( 'woocommerce_product_query_tax_query', 'custom_product_query_tax_query', 10, 2 );
function custom_product_query_tax_query( $tax_query, $query ) {
if( is_admin() ) return $tax_query;
if ( is_shop() ) {
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured'
);
}
return $tax_query;
}
代码位于活动子主题(或活动主题)的 function.php 文件中。已测试且有效。
首先你必须将 archive-product.php 模板覆盖到你的主题文件
然后添加以下代码以在商店 pahe 中显示特色产品。
<?php
$meta_query = WC()->query->get_meta_query();
$tax_query = WC()->query->get_tax_query();
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
);
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '5',
'orderby' => 'DESC',
'meta_query' => $meta_query,
'tax_query' => $tax_query,
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$id = $product->get_id();
$image_sale = wp_get_attachment_image_src( get_post_thumbnail_id( $loop->post->ID ), 'single-post-thumbnail' );
$product_url = get_permalink($id);
$product = wc_get_product($id);
$product_title = $product->get_title();
$sale_price = $product->get_price();
?>
<div class="item">
<div class="product-box">
<div class="product-img">
<a href="<?php echo $product_url;?>" title="" ><img src="<?php echo $image_sale[0]; ?>" data-id="<?php echo $id; ?>"></a>
</div>
<div class="product-content">
<h5><?php echo $product_title;?></h5>
<P>$<?php echo $sale_price;?>,00</P>
</div>
</div>
</div>
<?php
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
在functions.php中使用以下代码在商店页面中显示特色产品。
<?php
add_action( 'woocommerce_product_query', 'ss_custom_product_query' );
function ss_custom_product_query( $q ){
$meta_query = $q->get( 'meta_query' );
if ( is_shop() ) {
$meta_query[] = array(
'key' => '_featured',
'value' => 'yes'
);
}
$q->set( 'meta_query', $meta_query );
}
?>
执行此操作的一种方法是简单地编辑商店页面并使用简码:
[featured_products limit=”12″ columns=”4″]
这根本不会被装饰,所以你需要在上面添加一个标题: