You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce如何按星期几禁用特定分类下产品的购买按钮

按星期禁用指定父分类下所有产品购买按钮的实现方案

核心调整逻辑

  • 新增与站点时区对齐的星期判断条件,仅在匹配的禁用星期内执行后续操作
  • 优化产品分类匹配规则,可覆盖目标父分类下所有层级子分类关联的产品,解决原代码仅匹配直接关联分类、漏判子分类产品的问题

完整可直接复用的代码

add_action('woocommerce_single_product_summary', 'remove_product_description_add_cart_button', 1 );
function remove_product_description_add_cart_button() {
    // ========== 可自定义配置区域 ==========
    // 需禁用购买按钮的星期:0=周日、1=周一、2=周二、3=周三、4=周四、5=周五、6=周六
    $disabled_weekdays = array(1,2,3);
    // 目标父分类标识,支持填分类ID、slug、名称
    $target_parent_cats = array('ristorante-5');
    // ====================================

    // 第一步:判断当前是否为预设的禁用星期,不是则直接退出
    if ( ! in_array( current_time('w'), $disabled_weekdays ) ) return;

    global $product;
    if( ! $product ) return;

    // 获取当前产品关联的所有商品分类
    $product_cats = get_the_terms( get_the_id(), 'product_cat' );
    if( empty( $product_cats ) || is_wp_error( $product_cats ) ) return;

    // 将目标分类统一转换为ID格式,方便比对
    $target_cat_ids = array();
    foreach( $target_parent_cats as $target_cat ) {
        if( is_numeric( $target_cat ) ) {
            $target_cat_ids[] = (int)$target_cat;
            continue;
        }
        // 兼容slug、名称格式的分类配置
        $slug_term = get_term_by( 'slug', $target_cat, 'product_cat' );
        if( $slug_term ) $target_cat_ids[] = $slug_term->term_id;
        $name_term = get_term_by( 'name', $target_cat, 'product_cat' );
        if( $name_term ) $target_cat_ids[] = $name_term->term_id;
    }

    // 遍历产品关联分类,检查是否属于目标父分类(含所有子分类)
    $belongs_to_target = false;
    foreach( $product_cats as $cat ) {
        // 获取当前分类的所有上级祖先分类ID
        $ancestor_ids = get_ancestors( $cat->term_id, 'product_cat' );
        // 合并当前分类本身的ID,覆盖直接挂在父分类下的产品场景
        $related_cat_ids = array_merge( $ancestor_ids, array( $cat->term_id ) );
        if( array_intersect( $related_cat_ids, $target_cat_ids ) ) {
            $belongs_to_target = true;
            break;
        }
    }

    // 匹配到目标分类且在禁用星期内,移除加购按钮
    if( $belongs_to_target ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}

注意事项

  • 时间判断全部使用WordPress内置的current_time()函数,会自动对齐站点后台设置的时区,不会出现因服务器时区和站点时区错位导致的判断不准问题
  • 分类匹配逻辑会自动追溯分类层级,只要产品挂在目标父分类的任意层级子分类下,都会命中规则,无需单独为每个子分类配置
  • 可直接修改配置区域的两个数组,自定义需要禁用的星期、目标分类信息,不需要改动核心逻辑

内容的提问来源于stack exchange,提问作者Ratch Rint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 13:45:04