Skip to content

Instantly share code, notes, and snippets.

@hazrpg
Forked from yratof/functions.php
Created August 27, 2020 15:07
Show Gist options
  • Save hazrpg/e0bfdef657e92396dc099c275f367b82 to your computer and use it in GitHub Desktop.
Save hazrpg/e0bfdef657e92396dc099c275f367b82 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 );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment