简体   繁体   English

如何在没有其他插件的情况下按特色或标签对 WooCommerce 产品进行排序?

[英]How to sort WooCommerce product by featured or tag without additional plugins?

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.它与orderby 参数有关,但我不知道。

Please do not propose 3rd party plugins.请不要提出第 3 方插件。
More info in WooCommerce official docs . WooCommerce 官方 文档中的更多信息。

Product has a custom field as _featured which is set as yes for featured product and no for non-featured product.产品有一个自定义字段为_featured ,对于特色产品设置为yes ,对于非特色产品设置为no So you can use woocommerce_shortcode_products_query filter to overwrite WooCOmmerce shortcode.因此,您可以使用woocommerce_shortcode_products_query过滤器覆盖 WooCOMmerce 短代码。

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).代码进入活动子主题(或主题)的 function.php 文件中。 Or also in any plugin php files.或者也可以在任何插件 php 文件中。

USAGE用法
To list product form featured to non-featured (ie, form yes to no )列出产品形式的特色到非特色(即,从yesno

[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 .请注意::上面的代码似乎可以工作,但如果你打印$args['orderby']它没有显示_featured键,所以我硬编码,它在$args中。 It is not an standard way .这不是标准方式

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM