0

I would like the default sort method of my product archives to display all the featured products first, and then display all the other products as normal. I'm not sure if there is a hook for this or where to start.

Any ideas?

0

First display the product which is featured, then display the product which is not featured. Hope below code will helpful for you

    // Display featured Product first.
$query = new WP_Query( array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => -1 ,
    'tax_query' => array( array(
        'taxonomy' => 'product_visibility',
        'field'    => 'term_id',
        'terms'    => 'featured',
        'operator' => 'IN',
    ) )
) );

$featured_product_names = array(); // Initialize the array variable to display title
$featured_product_id = array(); // Initialize array to get the Featured Product id

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

        $product = wc_get_product( $query->post->ID );

        $featured_product_names[] = get_the_title(get_the_ID());
        $featured_product_id[]= get_the_ID();

endwhile; wp_reset_query();endif;

// Get the Other products.
$my_query = new WP_Query(array(
    'post__not_in' => $featured_product_id,// fetch other product which is not featured
    'post_type' => 'product'
));

if ( $my_query->have_posts() ): while ( $my_query->have_posts() ): $my_query->the_post();
    $featured_product_names[] = get_the_title(get_the_ID());
endwhile; wp_reset_query();endif;

// Testing output
echo '<p>Featured products: ' . implode(', ', $featured_product_names) . '</p>';
  • Thanks! I am not sure though how to use this to replace the default query? – Edegist Oct 10 '19 at 14:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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