kloon / WooCommerce-REST-API-Client-Library

A PHP wrapper for the WooCommerce REST API
GNU General Public License v3.0
356 stars 175 forks source link

Filter product by total sales #198

Closed martinappberg closed 8 years ago

martinappberg commented 8 years ago

Hi,

I am using this library but I can't figure out how to filter the products by total sales, and get the best selling products. I read something about a WP Query

<?php $args = array( 'post_type' => 'product', 'posts_per_page' => 4, 'meta_key' => 'total_sales', 'orderby' => 'meta_value_num', );

$loop = new WP_Query( $args ); if ( $loop->have_posts() ) { while ( $loop->have_posts() ) : $loop->the_post(); woocommerce_get_template_part( 'content', 'product' ); endwhile; } else { echo __( 'No products found' ); }

wp_reset_query();

?>

But I would need it to look similar to this:

$query_args = array( 'posts_per_page' => 8, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product', 'meta_query' => WC()->query->get_meta_query(), 'post__in' => array_merge( array( 0 ), wc_get_product_ids_on_sale() ) ); $products = new WP_Query( $query_args );

It would be amazing if anyone knew an easy way to do this, since there will be over 1000 products it needs to work really great.

Thanks in advance

martinappberg commented 8 years ago

Found a way, and this did the trick for me

$client = new WC_API_Client( $store_url, $consumer_key, $consumer_secret, $options );
    $args = array(
        //'filter[limit]' => 6,
        'filter[orderby]' => 'meta_value_num',
        'filter[order]' => 'DESC',
        'filter[orderby_meta_key]' => 'total_sales'
        );

    $products = $client->products->get(null, $args);

    echo json_encode($products);
jaythegeek commented 8 years ago

As you can see you are using WP Query, just in the URL instead of using the WP Query defined funstions in your PHP!

For those not using a wrapper, these parameters just need to be added to your request URL, for example;

https://example.com/wp-json/wc/v1/reports/sales?consumer_key=ck_*********************************&consumer_secret=cs_*********************************&filter[orderby_meta_key]=total_sales