Home > Enterprise >  Woocommerce programatically add and enable attributes
Woocommerce programatically add and enable attributes

Time:05-20

We have a Woocommerce website with over 1000 products on.

Is it possible to set a default attribute term for every product.

The attribute name is 'pa_arm-length' and the term is '1'.

So for example every single product would need an attribute enabled with a term of '1';

is this possible without having to go into every product individually, enable attribute and then assign it a term?

Expectation for each product

I can do it like this but it only works if the attribute already has a term assigned

wp_set_object_terms( $object_id, '1', 'pa_arm-length' , true);

Thanks in advance.

CodePudding user response:

i think this is what your looking for. this should add the pa_arm-length to every product with value 1. let me know if this works for you. you can also check this link for more details

$target_products = array(
     'post_type' => 'product',
     'post_status' => 'publish'
);

$my_query = new WP_Query( $args );

if( $my_query->have_posts() ) {

   while ($my_query->have_posts()) : $my_query->the_post(); 

     $term_taxonomy_ids = wp_set_object_terms( get_the_ID(), '1', 'pa_arm-length', true );
     $thedata = Array('pa_arm-length'=>Array(
       'name'=>'pa_arm-length',
       'value'=>'1',
       'is_visible' => '1',
       'is_taxonomy' => '1'
     ));
     update_post_meta( get_the_ID(),'_product_attributes',$thedata); 

   endwhile;
}

wp_reset_query();

CodePudding user response:

Ok so i have an update if this is helpful to anyone else.

The following need to be run inside the product loop.

$thedata = Array(
        'pa_arm-length' => Array(
        'name'=>'pa_arm-length',
        'value' => '1',
        'is_visible' => '1',
        'is_taxonomy' => '1'
        ), 
        'pa_lens-height' => Array(
        'name'=>'pa_lens-height',
        'value' => '1',
        'is_visible' => '1',
        'is_taxonomy' => '1'
        ), 
        'pa_bridge-size' => Array(
        'name'=>'pa_bridge-size',
        'value' => '1',
        'is_visible' => '1',
        'is_taxonomy' => '1'
        ), 
        'pa_color' => Array(
        'name' => 'pa_color',
        'value' => 'green',
        'is_visible' => '1',
        'is_taxonomy' => '1',
        'is_variation' => '1'
        ),
        'pa_size' => Array(
        'name' => 'pa_size',
        'value' => '48',
        'is_visible' => '1',
        'is_taxonomy' => '1',
        'is_variation' => '1'
        )
        
    );
     

    update_post_meta( get_the_ID(), '_product_attributes', $thedata);

For it to work i needed to include the existing attribute sets in the array (colour and size). That way it doesn't get overwritten when you run update_post_meta().

  • Related