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

WooCommerce可变产品自动预设可选属性默认值问题

WooCommerce:自动选中唯一可用的产品属性选项

你的问题出在给$args['selected']赋值时,传递了整个选项数组元素,而该参数需要的是选项的**value属性值**,不是完整的选项数组。修正后的代码如下:

add_filter('woocommerce_dropdown_variation_attribute_options_args', 'fun_select_default_option', 10, 1);

function fun_select_default_option($args) {
    // 过滤出所有未被禁用的可用选项
    $selectableOptions = array_filter($args['options'], function($option) {
        return !isset($option['disabled']) || !$option['disabled'];
    });

    // 仅当可用选项数量为1时自动选中
    if (count($selectableOptions) === 1) {
        $onlyOption = reset($selectableOptions);
        // 赋值选项的value值给selected参数
        $args['selected'] = $onlyOption['value'];
    }

    return $args;
}

代码说明:

  • 先通过array_filter筛选出所有未被禁用的选项,确保只统计真正可选的属性值
  • 当可用选项数量为1时,取出该选项的value属性(这是WooCommerce下拉框selected参数需要的正确格式)
  • 保持原逻辑的兼容性:当属性有多个可用选项时,不会自动选中任何选项

这个代码可以完美实现你需要的场景:

  • 产品1:尺码S、L缺货(禁用),M作为唯一可用选项会被自动选中;颜色仅蓝色可用,自动选中蓝色
  • 产品2:尺码全可用(数量>1),不会预设选中;颜色仅红色可用,自动选中红色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:03:28