Function.php配送日期代码不显示,需为三类商品添加配送日展示
问题排查与代码修正
原代码存在的问题
- 函数
BN_delievery_day定义在if条件判断内部,会导致钩子无法正确调用函数(函数只有条件满足时才会被定义,钩子注册时函数可能不存在)。 has_term仅判断了单个分类,未覆盖需求中的Cakes、Chocos Flavour、Fruits Flavour三类。date_default_timezone_set的参数多了冗余单引号,正确参数应为Asia/Kolkata。- 变量名拼写错误:
thresshold应为threshold,Delievery应为Delivery(规范写法)。
修正后的代码
function BN_delivery_day() { // 仅在商品页面执行 if ( ! is_product() ) return; // 定义需要显示配送日期的分类 $target_categories = array( 'Cakes', 'Chocos Flavour', 'Fruits Flavour' ); // 检查当前商品是否属于目标分类 if ( has_term( $target_categories, 'product_cat' ) ) { date_default_timezone_set( 'Asia/Kolkata' ); $threshold = '1800'; // 18:00 $current_time = date( "Hi" ); if ( $current_time < $threshold && $current_time > '0000' ) { $delivery_day = 'today'; } else { $delivery_day = 'tomorrow'; } echo '<p>Delivery: ' . $delivery_day . '</p>'; } } add_action( 'woocommerce_share', 'BN_delivery_day' );
代码说明
- 将函数定义移到条件判断外部,确保钩子能正确找到函数。
- 使用数组
$target_categories存储所有需要显示配送日期的分类,通过has_term一次性检查多个分类。 - 修复时区设置的单引号问题,修正拼写错误。
- 添加
is_product()判断,确保代码仅在单个商品页面执行,避免在其他页面无效输出。 - 用
<p>标签包裹输出内容,优化页面排版。
内容的提问来源于stack exchange,提问作者artsify in
相关产品推荐
相关产品推荐

