I'm using shortcode to list a product category like this
[product_category category="products" orderby="title" order="asc"]
And wonder how can I make featured products be on the top on the list? It has something to do with orderby parameter , but I have no idea.
Please do not propose 3rd party plugins.
More info in WooCommerce official docs .
Product has a custom field as
_featured
which is set asyes
for featured product andno
for non-featured product. So you can usewoocommerce_shortcode_products_query
filter to overwrite WooCOmmerce shortcode.
add_filter('woocommerce_shortcode_products_query', 'wh_woocommerce_shortcode_products_orderby');
function wh_woocommerce_shortcode_products_orderby($args)
{
$standard_array = ['menu_order', 'title', 'date', 'rand', 'id'];
// print_r($args['orderby']);
if (isset($args['orderby']) && !in_array($args['orderby'], $standard_array))
{
$args['meta_key'] = '_featured';
$args['orderby'] = 'meta_value_num';
}
// print_r($args);
return $args;
}
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
USAGE
To list product form featured to non-featured (ie, form yes
to no
)
[product_category category="products" orderby="_featured" order="DESC"]
Please Note:: above code seems to be working, but if you print $args['orderby']
it is not showing _featured
key, so I hardcoded, it in the $args
. It is not an standard way .
Hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.