Search code examples
wordpresswoocommerceproducthook-woocommercestock

Issue when using "woocommerce_product_get_stock_quantity" filter hook


I want to replace the stock quantity on the single product page with "5+", if the stock quantity is more than 5, else display the original quantity.

I tried to modify the hook as below

add_filter( 'woocommerce_product_get_stock_quantity' ,'custom_get_stock_quantity', 10, 2 );
add_filter( 'woocommerce_product_variation_get_stock_quantity' ,'custom_get_stock_quantity', 10, 2 );
function custom_get_stock_quantity( $value, $_product ) {
    global $product;

    if($_product->get_stock_quantity() > 5){
     return "5+";
    }
    else{
        return $_product->get_stock_quantity();
    }
}

This gives me 502 server error. What could be the issue here?


Solution

  • The error is due to several reasons

    • Hook is deprecated
    • Your callback function only returns a number: 5, not a string: "5+"
    • By using $_product->get_stock_quantity() you create an infinite loop, since this function calls the hook

    So to meet your demand, you will have to approach this differently. For example by using the woocommerce_get_availability_text hook

    So you get:

    // Availability text
    function filter_woocommerce_get_availability_text( $availability, $product ) {
        if ( $product->get_stock_quantity() > 5 ) {
            $availability = '+5';
        }
    
        return $availability; 
    }
    add_filter( 'woocommerce_get_availability_text', 'filter_woocommerce_get_availability_text', 10, 2 );