Sometimes we need to hide out of stock products in Woocommerce. When we visit a category page of products or all products shop page, all products show there. All products means stock/out of stock every products. The following code will hide the out of stock products. You can put this code into your plugin or theme functions file.
add_action( 'pre_get_posts', 'cwp_hide_out_of_stock_products' ); function cwp_hide_out_of_stock_products( $q ) { if ( ! $q->is_main_query() || is_admin() ) { return; } if ( $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ) ) { $tax_query = (array) $q->get('tax_query'); $tax_query[] = array( 'taxonomy' => 'product_visibility', 'field' => 'term_taxonomy_id', 'terms' => array( $outofstock_term->term_taxonomy_id ), 'operator' => 'NOT IN' ); $q->set( 'tax_query', $tax_query ); } remove_action( 'pre_get_posts', 'cwp_hide_out_of_stock_products' ); }
Leave a Comment
You must be logged in to post a comment.