Search code examples
phpwordpresswoocommerceproductproduct-variations

WooCommerce Output a text when chosen product variation is in stock


I've been rattling my head on how to add specific text through the variation.php template if a product variation's stock quantity is greater than zero.

The text is "Usually ships within 2-3 business days".

We take backorders, so if the stock is zero it can't display the text.

I'm able to display the text when each variation is selected with a function in the functions.php file:

add_filter( 'woocommerce_available_variation','load_variation_settings_fields' );
function load_variation_settings_fields( $variations ) {

    $variations['text_field'] = 'Usually ships within 2-3 business days'; 

    return $variations;
}

And adding this code to the variation.php template file:

<div class="woocommerce-variation-custom-text-field">
{{{ data.variation.text_field }}}
</div>

I'm having trouble grabbing the stock quantity of the variation selected and if it is greater than zero display the text edit- "Usually ships within 2-3 business days"edit.


Solution

  • Your custom function has 3 arguments that are enabled by the hook:

    • The the variation data array: $variation_data (that is returned)
    • The WC_Product_Variable object: $product
    • The WC_Product_Variation object: $variation

    So you can use the third argument to get the quantity for the current variation this way:

    add_filter( 'woocommerce_available_variation', 'load_variation_settings_fields', 10, 3 );
    function load_variation_settings_fields( $variation_data, $product, $variation ) {
    
        // Display shipping delay text when stock quantity exist
        if( $variation->get_stock_quantity() > 0 )
            $variation_data['text_field'] = __('Usually ships within 2-3 business days'); 
        else $variation_data['text_field'] = __(''); // You can add a text if needed
    
        return $variation_data;
    }
    

    Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

    This code is tested in WooCommerce version 3+ and works