我发现了这个问题,但没有人给出有效的答案: Woocommerce 设置默认变体
这里提到的不再起作用,我不明白错误是什么: https://quadlayers.com/default-product-attributes-woocommerce/
也许有人知道如何确保在输入可变产品时,至少选择了某些选项并且“添加到购物车”按钮处于活动状态?
不幸的是不再起作用的代码:
add_action('woocommerce_before_single_product_summary', 'quadlayers_product_default_attributes');
function quadlayers_product_default_attributes() {
global $product;
if (!count($default_attributes = get_post_meta($product->get_id(), '_default_attributes'))) {
$new_defaults = array();
$product_attributes = $product->get_attributes();
if (count($product_attributes)) {
foreach ($product_attributes as $key => $attributes) {
$values = explode(',', $product->get_attribute($key));
if (isset($values[0]) && !isset($default_attributes[$key])) {
$new_defaults[$key] = sanitize_key($values[0]);
}
}
update_post_meta($product->get_id(), '_default_attributes', $new_defaults);
}
}
}
我与 Claude AI 反复讨论这个问题并得到了有效的代码。我在这里分享它是因为它回答了一个问题,但也是为了看看是否有人对其生成的代码有任何疑问:
add_action('wp_footer', 'quadlayers_set_default_variations');
function quadlayers_set_default_variations() {
if (is_product()) {
global $product;
if ($product->is_type('variable')) {
$variations = $product->get_available_variations();
$default_variation = reset($variations);
$default_attributes = $default_variation['attributes'];
?>
<script>
jQuery(document).ready(function($) {
var defaultAttributes = <?php echo json_encode($default_attributes); ?>;
$('.variations_form').find('.variations select').each(function() {
var $select = $(this);
var attribute = $select.attr('name');
var value = defaultAttributes[attribute];
if (value) {
$select.val(value).trigger('change');
}
});
});
</script>
<?php
}
}
}