Skip to content

Instantly share code, notes, and snippets.

@yratof
Created December 7, 2016 16:01
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save yratof/f21242d4263c461f4a5b6b766cd24373 to your computer and use it in GitHub Desktop.
Save yratof/f21242d4263c461f4a5b6b766cd24373 to your computer and use it in GitHub Desktop.
Woocommerce remove unused attributes on product variations
<?php
add_action( 'init', function() {
ini_set( 'memory_limit', '2048M' );
set_time_limit( 0 );
$posts = get_posts( [
'post_type' => 'product',
'posts_per_page' => -1
] );
$count = 0;
foreach ( $posts as $post ) {
$product = get_product( $post );
if ( $product->product_type !== 'variable' ) {
continue;
}
$count ++;
$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'] ) ;
// var_dump( $terms );
foreach ( $terms as $term ) {
if ( in_array( $term->slug, $va[ $attribute['name'] ] ) ) {
// var_dump( $term );
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 );
}
}
wp_die( 'All attributes have been filtered: Total products changed: '. $count );
} );
@yratof
Copy link
Author

yratof commented Aug 21, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment