Order by custom Woocommerce product sorting in a WP_Query

前端 未结 1 1143
孤独总比滥情好
孤独总比滥情好 2021-01-25 06:46

I have created a shortcode to display products by category with the query below:

$atts = shortcode_atts( array (
        \'type\' => \'product\',
        \'po         


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 07:28

    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).

    0 讨论(0)
提交回复
热议问题