Skip to content

Instantly share code, notes, and snippets.

@yratof
Created December 7, 2016 16:01
Show Gist options
  • Select an option

  • Save yratof/f21242d4263c461f4a5b6b766cd24373 to your computer and use it in GitHub Desktop.

Select an option

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 );
} );
@moded-mike

moded-mike commented Aug 21, 2021

Copy link
Copy Markdown

This just throws back a critical error. As it's 5 years old, I guess its not compatible with the latest version of Wordpress. Anyone got a current solution?

@yratof

yratof commented Aug 21, 2021

Copy link
Copy Markdown
Author

The error is the key to solution - what is the error?

@moded-mike

Copy link
Copy Markdown

Just a generic 500 error. I think it's just timing out. I do have 17,000 products and 200,000 variations.

@yratof

yratof commented Aug 21, 2021

Copy link
Copy Markdown
Author

It will be most likely your server running out, but you can stop this script after 10 products instead of -1

@moded-mike

Copy link
Copy Markdown

Thanks. I've managed to remove the redundant attributes via a Bulk Editor that does it in batches of 100. All done in around 15 minutes.

@yratof

yratof commented Aug 21, 2021 via email

Copy link
Copy Markdown
Author

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