'Remove attributes not used for variations when saving product
I am importing products through CSV from a POS software and it is creating a lot of unnecessary attributes which are not used, and I would like to delete them automatically if they are not used for variations.
I found this code from another question which works great to process all my products.
But I would like to do it automatically for new products that will be imported in the future.
So I've wrote this code to delete the attributes not used for variations when a product is saved:
$postType = "product";
add_action("save_post_" . $postType, function ($post_ID, \WP_Post $post, $update) {
// Get the Variable product object (parent)
$product = wc_get_product($post_ID);
if ($product->is_type( 'variable' )){
$va = $product->get_variation_attributes();
$vas = [];
foreach ( $product->get_attributes() as $attribute ) {
if ( isset( $attribute['is_taxonomy'] ) && $attribute['is_taxonomy'] ) {
$terms = wp_get_post_terms( $product->id, $attribute['name'] ) ;
foreach ( $terms as $term ) {
if ( in_array( $term->slug, $va[ $attribute['name'] ] ) ) {
if ( ! isset( $vas[$attribute['name']] ) ) {
$vas[$attribute['name']] = [];
}
$vas[$attribute['name']][] = $term->term_id;
}
}
}
}
foreach ($vas as $tax => $vals) {
wp_set_post_terms( $product->id, $vals, $tax );
}
}
}, 10, 3);
I can see in the log that the code is executed (including the wp_set_post_terms function call), but the product attributes are not changed. Can you please help?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
