0

I have a little issue on wordpress with woocommerce. I have to check if a single product is best seller or not. So i crated one function who make query on product with meta_key = 'total_sales' and set the post_per_page = '10', because i want know the top 10 best seller and put a label "BEST SELLER" on product in shop page, and save the product ID inside an array. This is the php code of my function bestSellerArray() :

$post_type_query = new WP_Query( 
    array(
        'post_type'           => 'product',
        'post_status'         => 'publish',
        'ignore_sticky_posts' => 1,
        'posts_per_page'      => '10',
        'meta_key'            => 'total_sales',
        'orderby'             => 'meta_value_num',
        'meta_query'          => WC()->query->get_meta_query(),
        'tax_query'           => WC()->query->get_tax_query(),
        'category' => '',  
        'operator' => 'IN',         
    )
);
$products_ID = array();
while ($post_type_query->have_posts()){
    $post_type_query->the_post();  
    $products_ID[] = get_the_ID();
}
wp_reset_query();
return $products_ID;

Now, when the single products are shown in the shop i have to compare if the current product id is in array or not. If i call the function bestSellerArray() inside the content-product.php, who are request in the wp query inside the archive-product.php, i will see all time the same product, because the function's wp query alter the archive-product.php's query.

How i can make this?

Thanks to all

1
  • your problem is to retrieve the best sellers array or the current product identifier ?
    – mmm
    Nov 22, 2017 at 16:42

1 Answer 1

0

First you need to loop trough the posts, get all the 10 posts, based on their sales number.

Then, you need to check if the current product ID is equal to any ID of the products you looped.

If it is, then you show 'best seller' tag for the product.

In your code, you are probably mixing stuff.

Your code should be something like this:

$post_type_query = new WP_Query( 
array(
    'post_type'           => 'product',
    'post_status'         => 'publish',
    'ignore_sticky_posts' => 1,
    'posts_per_page'      => '10',
    'meta_key'            => 'total_sales',
    'orderby'             => 'meta_value_num', 
)
);
$products_ID = array();
while ($post_type_query->have_posts()){
    $post_type_query->the_post();  
    $products_ID[] = get_the_ID();
}
wp_reset_query();
return $products_ID;
$id = get_the_ID();
if (in_array($id, $products_ID)) {
    echo "Best Seller";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.