Get WooCommerce featured products in a WP_Query
This is an old question, but you can use wc_get_featured_product_ids() too:
$args = array(
'post_type' => 'product',
'posts_per_page' => $products,
'orderby' => $orderby,
'order' => $order == 'asc' ? 'asc' : 'desc',
'post__in' => wc_get_featured_product_ids(),
);
$query = new WP_Query( $args );
Just discovered it here. I hope it helps!
Since Woocommerce 3, you need to use a Tax Query instead as featured products are now handled by product_visibility
custom taxonomy for the term featured
:
// The tax query
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN', // or 'NOT IN' to exclude feature products
);
// The query
$query = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => $products,
'orderby' => $orderby,
'order' => $order == 'asc' ? 'asc' : 'desc',
'tax_query' => $tax_query // <===
) );
References:
- Official documentation
WP_Query
Taxonomy Parameters - Source code Woocommerce
WC_Shortcodes
featured_products()
function
You could use
wc_get_featured_product_ids()
function to get the featured product IDs array but using a tax query in aWP_Query
is just fine and the right way…
Related:
- Woocommerce meta_query not working for featured products
- Show only featured products in Woocommerce shop page
- Get featured products in Woocommerce 3
It should works.
You can now use wc_get_products with parameter featured set to true. See https://github.com/woocommerce/woocommerce/wiki/wc_get_products-and-WC_Product_Query
$args = array(
'featured' => true,
);
$products = wc_get_products( $args );
For people looking for getting featured products by category then you can check my notes about this => https://jameshwartlopez.com/plugin/get-featured-products-of-a-category/