Hello everyone!
In this article, I will talk about how to add an attribute to an attribute in WooCommerce. In the example below, we will add the “Outdoor” option to the “style” attribute of the products in the category with ID 501. You can change the code according to your needs or ask me for help by commenting.
If you are ready, let’s get started. The first thing you need to do is open your theme’s functions.php
file. You can do this via your panel or with an FTP client.
Add the following code to the end of your functions.php
file and wait a bit, then delete it. That’s it! When you run this code once, the “Outdoor” option will be added to the style attribute of all products in the category with ID 501.
function add_outdoor_to_style_attribute_in_category_products() {
$category_id = 501; // Your category ID
$attribute_slug = 'pa_style'; // Attribute Slug
// Get products in specified category
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category_id,
),
),
);
$products = get_posts($args);
// Add specified property to style attribute
foreach ($products as $product) {
$product_id = $product->ID;
$product_obj = wc_get_product($product_id);
$attributes = $product_obj->get_attributes();
// Check style attribute
if (isset($attributes[$attribute_slug])) {
$style_terms = wc_get_product_terms($product_id, $attribute_slug, array('fields' => 'names'));
// If it is not in the style attribute, add it
if (!in_array('outdoor', $style_terms)) {
$style_terms[] = 'outdoor'; // Add the attribute to the existing style values
wp_set_post_terms($product_id, $style_terms, $attribute_slug); // Save new style attribute
}
}
}
}
// Run the code in the admin panel
add_action('admin_init', 'add_outdoor_to_style_attribute_in_category_products');