By default woocommerce shortcodes doesn’t have the option to hide out of stock products. You can hide out of stocks products globally from Woocommerce settings but there is no option to hide/show it using product shortcodes for a single page etc. Below is a snippet that will add the ‘out_of_stock’ attribute in ‘products’ shortcode. Tested and works fine in Woocommerce 4+. May not work in woocommerce 3 or under.
//Add Out of stock attribute to Woocommerce shortcode add_filter('shortcode_atts_products', 'gabrics_shortcode_atts_products', 10, 4); function gabrics_shortcode_atts_products( $out, $pairs, $atts, $shortcode ){ if ( isset ($atts[ 'out_of_stock' ]) && $atts[ 'out_of_stock' ] == 0 ) { $out[ 'out_of_stock' ] = false; } else { $out[ 'out_of_stock' ] = true; } return $out; } //Filter products in shortcode in relation to out of stock attribute. add_filter( 'woocommerce_shortcode_products_query', function( $query_args, $atts, $loop_name ){ if( $loop_name == 'products' ){ $outofstock_term = get_term_by( 'name', 'outofstock', 'product_visibility' ); if(isset($atts['out_of_stock']) && $atts['out_of_stock'] == false ) { $query_args['tax_query'] = array( array( 'taxonomy' => 'product_visibility', 'field' => 'term_taxonomy_id', 'terms' => array( $outofstock_term->term_taxonomy_id ), 'operator' => 'NOT IN' ) ); } } return $query_args; }, 10, 3);
You can now add out of stock attribute in shortcodes like [products category=”jeans” out_of_stock=”0″]
0 For hiding out of stock products and 1 for showing.
Recent Comments