Search code examples
wordpresswoocommercehook-woocommercecustom-code

Display featured products first and Out of stock products at last in shop page


I need to display the featured products in top of the shop page and also needs to display out of stock products in the bottom of the list.

I am able to make the out of stock products in the bottom with the following code but it re-orders the featured product along with it.

add_action( 'pre_get_posts', function ( $q ) {
    if (   is_shop()                  // Target only front end 
         && $q->is_main_query()        // Only target the main query
         && $q->is_post_type_archive() // Change to suite your needs
    ) {
        $q->set( 'meta_key', '_stock_status' );
        $q->set( 'orderby',  'meta_value'    );
        $q->set( 'order',    'ASC'           );
    }
}, PHP_INT_MAX );

Is there a way through which I can achieve both?

Please help me in it.

Thanks.


Solution

  • It is late to answer this question, maybe someone else need:

    add_filter('posts_clauses', 'custom_order_by_stock_status', 10, 2);
    function custom_order_by_stock_status($posts_clauses, WP_Query $query) {
        global $wpdb;
    
        if ( $query->is_main_query() && (is_shop() || is_product_taxonomy()) ) {
            $featured_ids = wc_get_featured_product_ids();
            $posts_clauses['join'] .= " LEFT JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '') ";
            $posts_clauses['orderby'] = " if($wpdb->posts.ID in (0".(implode(",", $featured_ids))."), 0, 1), istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
        }
        return $posts_clauses;
    }