通过WP_Query中的自定义Woocommerce产品排序来排序 [英] Order by custom Woocommerce product sorting in a WP_Query
问题描述
我创建了一个短代码,用于通过以下查询按类别显示产品:
I have created a shortcode to display products by category with the query below:
$atts = shortcode_atts( array (
'type' => 'product',
'posts' => -1,
'category' => '',
), $atts, 'list_products' );
$query = new WP_Query( array(
'post_type' => $atts['type'],
'posts_per_page' => $atts['posts'],
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
) ),
) );
This is all fine, however I am trying to use the order by attribute when I sort the products using the custom sort shown here
我从两个问题:
使用自定义排序时,我需要使用哪个属性进行排序
Which attribute do I need to use to sort when using custom sorting
还有
添加到上述查询中后,我该怎么做才能使我的orderby
属性起作用?因为我使用过的那个属性值始终按发布的降序进行排序.
What do I need to do to make my orderby
attribute work when added to the above query? Because it which ever attribute value I use it always sorts by published descending.
推荐答案
在对Woocommerce产品使用自定义排序时,它会在menu_order
列下的wp_posts
数据库表中为每种产品设置一些值.
When you use custom sorting for Woocommerce products, it set some values for each product in wp_posts
database table under menu_order
column.
然后,您只需要在WP_Query
中添加'orderby' => 'menu_order',
,在代码中:
Then you just need to add 'orderby' => 'menu_order',
in your WP_Query
, so in your code:
$atts = shortcode_atts( array (
'type' => 'product',
'posts' => -1,
'category' => '',
), $atts, 'list_products' );
$query = new WP_Query( array(
'post_type' => $atts['type'],
'posts_per_page' => $atts['posts'],
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $atts['category'],
) ),
'orderby' => 'menu_order',
// 'order' => 'DESC',
) );
它将起作用(默认情况下,order
排序参数通常设置为ASC
).
It will work (by default the order
sorting argument is set to ASC
normally).
这篇关于通过WP_Query中的自定义Woocommerce产品排序来排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!