简体   繁体   中英

How to get best selling products using wp_query woocommerce last week and last month

I want to get Best selling Products on Home page sort by last week and last month. I am using Below query But this is not getting best selling products from all categories.

function get_product_posts_hp(){
    $query = new WP_Query( array(
        'posts_per_page' => 12,
        'post_type' => 'product',
        'post_status' => 'publish',
        'ignore_sticky_posts' => 1,
        'meta_key' => 'total_sales',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
    ) );

    echo '<p>Count: '. $query->post_count ; '</p>';

    if($query->have_posts()) :
        while($query->have_posts()) : $query->the_post();

            echo '<p>' . get_the_title() . ' (';
            echo get_post_meta( get_the_id(), 'total_sales', true) . ')</p>';

        endwhile;
        wp_reset_postdata();
    endif;
}

Your query is not the best way to get this becouse you want to have period of time. You have to use post type shop_orders get all orders with complete status for specific period , then break the order items in the order as items and you will get the best sellers for period of time. Or if you dont want a period of time then you can add this in your query

    $query = new WP_Query( array(
    'posts_per_page' => 12,
    'post_type' => 'product',
    'post_status' => 'publish',
    'ignore_sticky_posts' => 1,
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'meta_query'=> array(
    array(
      'key' => 'total_sales',
      'compare' => '>=',
      'value' => 1,
      'type' => 'numeric',
    )
  )
) );

At value you can change how many total sales this products must have atleast :)

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.

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