• Resolved artemis21

    (@artemis21)


    Hello,
    If I have a variable product with only one option available, I’d like to have that option pre selected.

    I tried:

    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;
    }
    

    This works if a dropdwown has only one option and that option is available. But not if there’s 3 and one available.

    So I tried filtering out available options but still does not work:

    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;
    }
    

    How can I pre-select if only one option for attribute is available and only if there is a variation matching those terms?

    Thank you

Viewing 1 replies (of 1 total)
  • Hi there,

    Thanks again for getting back to us!

    How can I pre-select if only one option for attribute is available and only if there is a variation matching those terms?

    Helping out with custom coding of this nature is outside the scope of support that we can help out with here, although I would recommend the following:

    1. Running the exact question you’re asking, along with the code provided, through an AI platform like ChatGPT for recommendations/changes to your code.
    2. Checking whether there are existing plugins in the WordPress plugin repository that might be doing that already.
    3. Joining our WooCommerce Slack community (it does have a developer channel where you can ask coding questions): https://woo.com/community-slack/
    4. Hiring a WooCommerce Expert

    Hope it helps!

Viewing 1 replies (of 1 total)

The topic ‘WooCommerce pre select product attribute’ is closed to new replies.