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

WooCommerce如何实现选中一个属性后禁用另一个属性

解决WooCommerce颜色属性与定制颜色属性互斥问题

自定义JavaScript实现二选一互斥逻辑

假设你已经在WooCommerce后台创建了Color(slug为pa_color)和Color Special Order(slug为pa-color-special-order)两个属性并添加到目标产品中,可通过以下代码实现互斥效果:

  1. 添加代码到主题文件
    打开当前使用的主题(建议用子主题,避免主题更新丢失代码)的functions.php文件,插入以下代码:
add_action( 'wp_footer', 'woocommerce_mutually_exclusive_attributes' );
function woocommerce_mutually_exclusive_attributes() {
    if ( ! is_product() ) return;
    ?>
    <script>
    jQuery(document).ready(function($) {
        // 替换为你实际的属性选择器,根据属性slug调整
        const colorAttr = 'select[name="attribute_pa_color"]';
        const specialColorAttr = 'select[name="attribute_pa-color-special-order"]';

        // 选中Color后禁用定制颜色选项并清空值
        $(colorAttr).on('change', function() {
            if ($(this).val()) {
                $(specialColorAttr).prop('disabled', true).val('');
            } else {
                $(specialColorAttr).prop('disabled', false);
            }
        });

        // 选中定制颜色后禁用Color选项并清空值
        $(specialColorAttr).on('change', function() {
            if ($(this).val()) {
                $(colorAttr).prop('disabled', true).val('');
            } else {
                $(colorAttr).prop('disabled', false);
            }
        });
    });
    </script>
    <?php
}
  1. 适配调整
  • 代码中的属性slug(pa_color、pa-color-special-order)要和后台创建的属性slug完全匹配,可在「WooCommerce > 属性」页面查看对应slug。
  • 若属性使用的是单选按钮而非下拉选择框,把选择器改成input[name="attribute_pa_color"],事件监听改为click即可。
  1. 测试验证
    保存代码后清空浏览器缓存,打开产品页面测试:选中其中一个属性,另一个会自动禁用并清空已选内容;取消选择后,被禁用的属性会恢复可用状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:25:30