自动定义 WooCommerce 可变产品上的默认选定属性值

问题描述 投票:0回答:1

在 WooCommerce 中,如果我的产品只有一个可用选项,我需要预先选择它。

我尝试过:

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

function fun_select_default_option($args) {
    if (count($args['options']) === 1) {
        $onlyOption = reset($args['options']);
        if (!isset($onlyOption['disabled']) || !$onlyOption['disabled']) {
            $args['selected'] = $onlyOption;
        }
    }
    return $args;
}

如果下拉菜单只有一个选项并且该选项可用,则此方法有效。但如果有 3 个和 1 个可用则不然。

所以我尝试过滤掉可用的选项,但仍然不起作用:

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'];
    });

    if (count($selectableOptions) === 1) {
        $onlyOption = reset($selectableOptions);
        $args['selected'] = $onlyOption;
    }

    return $args;
}

如果只有一个属性选项可用,则应预先选择。

php wordpress woocommerce hook-woocommerce product-variations
1个回答
0
投票

要自动定义可变产品的默认变体属性,您可以使用以下命令:

add_filter( 'woocommerce_product_get_default_attributes', 'auto_define_default_variation_attributes', 10, 2 );
function auto_define_default_variation_attributes( $default_attributes, $product ){
    $variation_attributes = $product->get_variation_attributes();

    // Loop through available variations
    foreach( $product->get_available_variations('objects') as $variation ) {
        // Target purchasable variation
        if ( $variation->is_purchasable() ) {
            // Loop through attributes for the current variation
            foreach( $variation->get_attributes() as $attribute => $value ) {
                if ( ! empty($value) ) {
                    $default_attributes[$attribute] = $value;
                } else {
                    // If there is no defined value, set it
                    foreach( $variation_attributes as $variation_attribute => $values ) {
                        if ( $attribute === sanitize_title($variation_attribute) ) {
                            $default_attributes[$attribute] = current($values);
                            break;
                        }
                    }
                }
            }
            break; // Stop the loop
        }
    }
    return $default_attributes; // Always return the values in a filter hook
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。

注意: 代码处理 WooCommerce 产品属性和变体的自定义属性。

© www.soinside.com 2019 - 2024. All rights reserved.