Add Attribute to WooCommerce Product Programmatically

In the world of web development, anything can happen, for instance and the sake of this article, let’s say you’re working with a team utilizing git and for some reason all attributes of a given product have gone missing and your task is to get these attributes back to where they were.  You could do this manually, but why not dive into some code and replace those missing attributes?

Step 1: Get all products and store in an array

        global $product;
	$taxonomy = 'pa_greeting-card-type';
	$term_name = 'holiday';
	$term_slug = sanitize_title($term_name); // The term "slug"
	$product_ids = [];
	$args = array(
		'post_type' => 'product',
			'posts_per_page' => 70,
			'tax_query' => array(
					'taxonomy' => 'product_tag',
					'field' => 'slug',
					'terms' => array('mothers-day-card', 'valentines-day-card', 'christmas-cards', 'holiday-card', 'new-year-card', 'jewish-card', 'easter-cards', 'new-year' 

	$loop = new WP_Query($args);
	while ($loop->have_posts()) : $loop->the_post();
			global $product;
			$flag = 0;
			// get product attributes
			$attributes = $product->get_attributes();
				$product_ids[] = get_the_ID(); //products with no attributes
			// if it has product attributes
			else {
				//looping through all product attributes
				foreach($attributes as $attribute) :
					 echo $attribute['name'];

					if($attribute['is_taxonomy']) {
						if($attribute['name'] == $term_name){
							$flag = 1;
				if ($flag != 1) {
					$product_ids[] = get_the_ID();  //products from our loop without our missing attributes


Step 2: Loop through products adding our missing attribute

$product_ids will contain all the Product IDs which do not have our missing attribute, so now we can loop through and set that missing attribute.

		foreach ($product_ids as $product_id) {
		// Check if the term exist and if not it create it (and get the term ID).
		if( ! term_exists( $term_name, $taxonomy ) ){
		    $term_data = wp_insert_term( $term_name, $taxonomy );
		    $term_id   = $term_data['term_id'];
		} else {
		    $term_id   = get_term_by( 'name', $term_name, $taxonomy )->term_id;

		//Initialize new object
		$product = wc_get_product( $product_id );

    	        $attribute = new WC_Product_Attribute();
		$attributes[] = $attribute;



		// Append the new term in the product
		if( ! has_term( $term_name, $taxonomy, $product_id )) {
		    wp_set_object_terms($product_id, $term_slug, $taxonomy, true );

Step 3: Go kiss your loved ones, you’re done here


Please feel free to comment and let you know if this got you on the right track!