Order by custom Woocommerce product sorting in a WP_Query

心不动则不痛 提交于 2019-12-20 03:49:13

问题


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

I have added: 'orderby' => 'modified', and tried some others from here.

Two questions:

Which attribute do I need to use to sort when using custom sorting

And

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.


回答1:


When you use custom sorting for Woocommerce products, it set some values for each product in wp_posts database table under menu_order column.

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',
) );

It will work (by default the order sorting argument is set to ASC normally).



来源:https://stackoverflow.com/questions/50937078/order-by-custom-woocommerce-product-sorting-in-a-wp-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!