newsletter emailing

Stay on top with regular WordPress updates.

Subscribe to our newsletter(s) and get the latest stories in your mailbox!

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

Author:

Date:

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.

This is the first part of the article

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

wpforms banner 01 468x602x