简体   繁体   中英

Add to Out-of-stock availability text, an availability date in Woocommerce single products

I have following code that adds a simple notice to a single product:

add_action( 'woocommerce_after_add_to_cart_form', 'acf_field_description', 15 );

function acf_field_description() {
    global $product;

    if ( ! $product->is_in_stock() ) {
        echo '<div style="color: red;"><strong>' . __('Product will be available from: ', 'flatsome') . '</strong>' . get_field('date_of_availability') . '</div>';
    } else {
        echo __('Product is available', 'flatsome');
    }
}

If statement is not working, but else statement works perfect.

What I am doing wrong? Any help is appreciated.

First, It seems that you have created a product custom date field date_of_availability using Advanced Product Fields (ACF) Plugin.

WooCommerce has already a stock availability feature display in products, try the following code instead:

// Change product availability text
add_filter( 'woocommerce_get_availability_text', 'filter_product_availability_text', 10, 2);
function filter_product_availability_text( $availability, $product ) {
    $date_of_availability = get_field('date_of_availability');

    if ( ! $product->is_in_stock() && ! empty($date_of_availability) ) {
        $availability .= '<span style="color:#e2401c;"><strong>- (' . __('Available from:', 'flatsome') . ' </strong>' . get_field('date_of_availability') . ')</span>';
    }
    return $availability;
}

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

Changed Out of stock availability display, with defined date of availability:

在此处输入图片说明


Default WooCommerce in stock availability display:

在此处输入图片说明

Availability: There are some related settings in Woocommerce Settings > Products > Inventory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM