Reputation: 23
I am using simple and variations products with active manage stock.
I need to list only products with stock quantity > 0 in frontend search and categories.
I am trying the follow code, but does not work.
add_action( 'pre_get_posts', 'show_only_products_with_qtdy_min_1' );
function show_only_products_with_qtdy_min_1( $query ) {
// $query->is_search
if( ! is_admin() && $query->is_main_query() && $query->query_vars['post_type'] == 'product' ) {
//Get original meta query
$meta_query = $query->get('meta_query');
// Add your criteria
$meta_query[] = array(
'key' => '_stock_quantity',
'value' => 0,
'compare' => '>'
);
// print_r($meta_query); exit();
// Set the meta query to the complete, altered query
$query->set('meta_query',$meta_query);
}
};
Upvotes: 1
Views: 5708
Reputation: 782
I'm using this code snippet and worked:
function 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', 'hide_out_of_stock_products' );
}
add_action('pre_get_posts', 'hide_out_of_stock_products');
Upvotes: 0
Reputation: 253919
Your issue is due to 'key' => '_stock_quantity',
that should be instead 'key' => '_stock',
…
Now you can use the dedicated Woocommerce filter:
add_filter( 'woocommerce_product_query_meta_query', 'show_only_products_with_qtdy_min_1', 10, 2 );
function show_only_products_with_qtdy_min_1( $meta_query, $query ) {
if( is_admin() ) return $meta_query;
// Add your criteria
$meta_query[] = array(
'key' => '_stock',
'type' => 'numeric',
'value' => 0,
'compare' => '>'
);
return $meta_query;
};
Or your code:
add_action( 'pre_get_posts', 'show_only_products_with_qtdy_min_1' );
function show_only_products_with_qtdy_min_1( $query ) {
// $query->is_search
if( ! is_admin() && $query->is_main_query() && $query->query_vars['post_type'] == 'product' ) {
$meta_query = $query->get('meta_query'); // Get original meta query
// Additional meta query
$meta_query[] = array(
'key' => '_stock',
'type' => 'numeric',
'value' => 0,
'compare' => '>'
);
// Set back the altered meta query
$query->set('meta_query',$meta_query);
}
};
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works.
Upvotes: 3