retrieve thumbnail from post ID of best selling product in category

What I understood from your question is, you want to get the best seller product in each category and set its image as a category thumb.

you will need to loop through all categories then you will need also a nested loop in each category for the best product in the current loop of categories, then you will have the access to the best seller product image.

the following code will describe more (UnTested):


$terms = get_terms( 'product_cat', array(
    'hide_empty' => false,
) );

foreach ( $terms as $term ) {
    $query = new WP_Query( [
        'post_type'      => 'product',
        'posts_per_page' => 1,
        'meta_key'       => 'total_sales',
        'orderby'        => 'meta_value_num',
        'tax_query'      => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => $term->slug,
            ),
        ),
    ] );
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            $thumbnail="DEFAULT THUMBNAIL ID";
            if ( has_post_thumbnail() ) {
                $thumbnail = get_post_thumbnail_id();
                //THEN YOU WILL BE ABLE TO SET THE CATEGORY THUMBNAIL WITH THIS PRODUCT THUMBNAIL ID
            }
        }
    }
    wp_reset_postdata();
}

Leave a Comment