'Show only featured products in Woocommerce shop page
I want to display in default shop page from WooCommerce only featured products, nothing more... It's there a solution to display in WooCommerce shop template only the featured products?
Solution 1:[1]
You should use this custom function hooked in woocommerce_product_query_tax_query
filter hook, that will display only featured product in shop (but not in other archives pages):
// 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;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Solution 2:[2]
First you have to override archive-product.php template to your theme file
then add below code to display featured product in shop 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();
?>
Solution 3:[3]
Use the following code in your functions.php to display featured products in the shop page.
<?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 );
}
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | LoicTheAztec |
Solution 2 | PPL |
Solution 3 | Shashank Sharma |