• Resolved Luca F.

    (@lucafriso)


    When a Vendor inserts a product I need a certain attribute to be automatically set with a default value. As Admin, with the standard woocommerce entry form, I easily solved it with this code in functions.php

    function make_product_attribute($name) {
        global $wc_product_attributes;
        if ( isset($wc_product_attributes[$name]) ){
            $newattr = new WC_Product_Attribute();
            $newattr->set_id(1);  //any positive value is interpreted as is_taxonomy=true
            $newattr->set_name($name);
            $newattr->set_visible(true);
            $newattr->set_variation(true);
            //example of setting default value for item
            if ($name=='pa_condizione'){
                $terms = get_terms("pa_condizione");
                foreach ($terms as $term) {
                    $term = get_term_by('slug', $term->name, $name);
                }
                $newattr->set_options(array(1452)); //Global attribute term IDs previously added from Products->Attributes
            }
            return $newattr;
        } else {
            return false;
        }
    }
    
    function default_product_attributes() {
        global $product;
        if (! $product) {
            $product = $GLOBALS['product_object'];
        }
        if (! $product) {
            return;
        }
        $attributes = $product->get_attributes();
        
        $defaultAttributes = array(
            'pa_condizione'
        );
        
        $changed=false;
        foreach ($defaultAttributes as $key){
            if (! isset($attributes[$key])){
                $newattr = make_product_attribute($key);
                if ($newattr){
                    $attributes[$key] = $newattr;
                }
                $changed = true;
            }
        }
        if ($changed){
            $product->set_attributes($attributes);
        }
    }
    add_action('woocommerce_product_write_panel_tabs', 'default_product_attributes');

    From the vendor dashboard however it doesn’t work. How could I integrate this function for Vendors as well?

    Thanks for any help.

Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Preset attributes in product entry’ is closed to new replies.