Home > database >  WooCommerce how to check if the product is in stock
WooCommerce how to check if the product is in stock

Time:10-18

I think there is quite an easy solution:

In WooCommerce I want to apply my delivery time filter to a single product, but only if it is available/in stock. I am getting an error when it comes to any kind of checking the products stock.

function filter_woocommerce_germanized_delivery_time_html( $str_replace, $html ) { 
    
    global $product;
if( $product->is_in_stock() ) {

        echo '<p >';
        echo $str_replace;
        echo '</p>'; 
    echo '<p ><a href="https://xyz.at/info/lieferzeiten/" target="_blank"><i ></i> EU-Lieferzeiten</a></p></span>';
    
}
    
}   
         
// add the filter 
add_filter( 'woocommerce_germanized_delivery_time_html', 'filter_woocommerce_germanized_delivery_time_html', 10, 2 );

I also tried:

if($product->get_stock_quantity()>0) 

But similar errors like:

"Uncaught Error: Call to a member function is_in_stock() on null.."

Thanks for the help!

Regards, Felix

CodePudding user response:

The error is telling you that you used your function on a null value which means it could not find the $product variable.

Not sure where this woocommerce_germanized_delivery_time_html filter hook comes from and where you're using global $product, but you could use the following snippet to get the product.

global $post;
$product = wc_get_product($post->ID);

Now your entire code would be something like this:

add_filter( 'woocommerce_germanized_delivery_time_html', 'filter_woocommerce_germanized_delivery_time_html', 10, 2 );

function filter_woocommerce_germanized_delivery_time_html($str_replace, $html)
{

    global $post;

    $product = wc_get_product($post->ID);

    if ($product->is_in_stock()) {

        echo '<p >';
        echo $str_replace;
        echo '</p>';
        echo '<p >';
        echo '<a href="https://xyz.at/info/lieferzeiten/" target="_blank"><i ></i> EU-Lieferzeiten</a>';
        echo '</p>';
    } else{
       return $str_replace;
    }

}

Or you could get the stock quantity like this:

add_filter( 'woocommerce_germanized_delivery_time_html', 'filter_woocommerce_germanized_delivery_time_html', 10, 2 );

function filter_woocommerce_germanized_delivery_time_html($str_replace, $html)
{

    global $post;

    $stock_quantity = get_post_meta($post->ID, '_stock', true);

    if ($stock_quantity > 0) {

        echo '<p >';
        echo $str_replace;
        echo '</p>';
        echo '<p >';
        echo '<a href="https://xyz.at/info/lieferzeiten/" target="_blank"><i ></i> EU-Lieferzeiten</a>';
        echo '</p>';
    } else {
       return $str_replace;
    }

}

Let me know if you could get it to work!

  • Related