在WooCommerce中,我想在有限的时间内开设销售,例如“添加到购物车”按钮仅显示3小时,并在其他所有时间内隐藏。
我现在可以使用remove_action()删除添加到购物车按钮,这样:
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
但如何在一小时范围内隐藏它?这可能吗?
任何帮助将不胜感激。
答案 0 :(得分:2)
以下代码将在第一个函数中定义小时范围内的“添加到购物车”按钮。您还必须定义商店位置的时区。获得specific timezone。
在那个小时范围之外:
代码:
// Conditional time function (Define: start and end time / Timezone)
function conditional_hours_range(){
// HERE below, define start / end hours range and time zone (default is 'UTC').
$start_hour = 13;
$end_hour = 16;
date_default_timezone_set ('Europe/Paris');
$now = strtotime("now"); // Now time
$today_time = strtotime(date("Y-m-d")); // Today time at 00:00
$starting_time = $today_time + ( $start_hour * 3600 );
$ending_time = $today_time + ( $end_hour * 3600 );
// return true or false
return $now >= $starting_time && $now <= $ending_time ? false : true;
}
// Replacing the button add to cart by a link to the product in Shop and archives pages
add_filter( 'woocommerce_loop_add_to_cart_link', 'replace_loop_add_to_cart_button', 10, 2 );
function replace_loop_add_to_cart_button( $button, $product ) {
// Only on custom hour range
if( conditional_hours_range() ){
$button_text = __( "View product", "woocommerce" );
$button = '<a class="button" href="' . $product->get_permalink() . '">' . $button_text . '</a>';
}
return $button;
}
// Replacing the button add to cart by an inactive custom button
add_action( 'woocommerce_single_product_summary', 'replace_single_add_to_cart_button', 1 );
function replace_single_add_to_cart_button() {
// Only on custom hour range
if( conditional_hours_range() ){
global $product;
// For variable product types (keeping attribute select fields)
if( $product->is_type( 'variable' ) ) {
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
add_action( 'woocommerce_single_variation', 'custom_disabled_button', 20 );
}
// For all other product types
else {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
add_action( 'woocommerce_single_product_summary', 'custom_disabled_button', 30 );
}
}
}
// The custom replacement inactive button
function custom_disabled_button(){
$button_text = __( "Soon enabled", "woocommerce" );
$style = 'style="background:Silver !important; color:white !important; cursor: not-allowed !important;"';
echo '<a class="button" '.$style.'>' . $button_text . '</a>';
}
代码放在活动子主题(或活动主题)的function.php文件中。
经过测试和工作