skip to Main Content

I’m having a hard time to automatically hide some products based on id from shop loop, search etc if the stock drops bellow a specific number.
I’m trying to do this because I’m trying to reserve lets say 20 items from that product so they can be sold elsewhere.

functions.php

add_filter( 'pre_option_woocommerce_hide_out_of_stock_items', 'set_out_of_stock_product_qty_less_than' );
function set_out_of_stock_product_qty_less_than( $hide ) {
    global $product;
    
    $product_id = 2004891;
    $product = wc_get_product($product_id);
    $stock = $product->get_stock_quantity();
    
    //$prodid = $product->get_id();
    //$stock = $product->get_stock_quantity();
    if ( $stock <= 174) {
        $hide = 'yes';
    }
    return $hide;
}

2

Answers


  1. add_action('woocommerce_product_query', 'hide_specific_products_from_shop', 20, 2);
    
    function hide_specific_products_from_shop($q, $query) {
        if (is_admin())
            return;
    
        $product_id = 2004891;
        $product = wc_get_product($product_id);
        $stock = $product->get_stock_quantity();
    
        if ($stock <= 176) {
            $q->set('post__not_in', array($product_id));
        }
    }
    
    Login or Signup to reply.
  2. You can hide from shop page through this hook

    add_action( 'woocommerce_product_query', 'woo_custom_product__query' );
    function woo_custom_product_query( $q ) {
        $meta_query = $q->get( 'meta_query' );
    
        $meta_query[] = array(
            'key'       => '_stock',
            'value'     => '5', // your prefered stock value
            'compare'   => '>'
        );
    
        $q->set( 'meta_query', $meta_query );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search