WP SITES

3082 Coded Tutorials & 283 Plugins

Hide Out of Stock Products On Shop Page Archives When Sorting by Specific Parameters

This code hides products which are out of stock when sorting on the shop and category archive pages by price and popularity.

add_action( 'woocommerce_product_query', 'wpsites_hide_out_of_stock_products_on_specific_sorting', 10, 2 );
function wpsites_hide_out_of_stock_products_on_specific_sorting( $query ) {

    if ( ! is_admin() && $query->is_main_query() && is_shop() || is_product_category() ) {
    
        $orderby = isset( $_GET['orderby'] ) ? wc_clean( wp_unslash( $_GET['orderby'] ) ) : '';

        if ( in_array( $orderby, array( 'price', 'popularity' ) ) ) {
        
            $query->set( 'meta_query', array_merge( $query->get( 'meta_query' ), array(
                array(
                    'key'     => '_stock_status',
                    'value'   => 'instock',
                    'compare' => '='
                )
            ) ) );
        }
    }
}

You can also use pre_get_posts.

Leave a Reply

New Plugins