user14206638
user14206638

Reputation:

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;
}

Upvotes: 0

Views: 1501

Answers (1)

Snuffy
Snuffy

Reputation: 2096

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

Upvotes: 2

Related Questions