在 Woocommerce 单页中无法购买产品时显示自定义消息 [英] Display a custom message when a product is not purchassable in Woocommerce single pages
问题描述
我正在创建一个花店网站.有些鲜花是季节性的.使用
<小时>您也可以用短文本代替禁用按钮,在我的代码中替换:
echo ''.__("此产品当前不可用.") .'</p>';
这样:
echo '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.
解决方案 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.
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>';
这篇关于在 Woocommerce 单页中无法购买产品时显示自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!