phpwordpresswoocommerceproductavailability

Display a custom message when a product is not purchassable in Woocommerce single pages


I am creating a website which is flower shop. Some flowers are seasonally available. Using Advanced Custom Fields plugin, I have added a custom field in Woocommerce product post type (check box) list of months to chose from in which product will be available.

I have been able to disable the add to cart button for the months in which product will not be available using code below:

add_filter('woocommerce_is_purchasable', 'is_available', 10, 2);
function is_available() {
    // this is a field added using 'Advance Custom Fields' plugin 
    $months = get_field('availability');
    $currentMonth = date('F');

    if(in_array($currentMonth, $months))
        return true;
    else
        return false;
}

The code I'm using works, it removes add to cart button from the related single product page. I would like to add some message, so customers will know why it's not available. How can I do that?

I just need to know how I can add message as well, when the product is not available.


Solution

  • There are some errors in your code, like the 2 missing function variables declared for this hook.

    The following revisited code includes the displayed custom message, when the product is not available:

    add_filter('woocommerce_is_purchasable', 'woocommerce_is_purchasable_filter_callback', 10, 2 );
    function woocommerce_is_purchasable_filter_callback( $purchasable, $product ) {
        $months      = (array) get_field('availability');
        $purchasable = in_array( date('F'), $months ) ? $purchasable : false;
    
        return $purchasable;
    }
    
    add_action( 'woocommerce_single_product_summary', 'unavailable_product_display_message', 20 );
    function unavailable_product_display_message() {
        global $product;
    
        if(! $product->is_purchasable() ){
            echo '<p style="color:#e00000;">' . __("This product is currently unavailable.") . '</p>';
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    enter image description here


    You can also display instead a disabled button with a short text, replacing in my code:

    echo '<p style="color:#e00000;">' . __("This product is currently unavailable.") . '</p>';
    

    By this:

    echo '<a class="button alt disabled">' . __("Currently unavailable.") . '</a>';
    

    enter image description here