Skip to content

Instantly share code, notes, and snippets.

@twoelevenjay
Last active April 13, 2016 20:47
Show Gist options
  • Save twoelevenjay/88c69ff8923428fa4a121fd8149dc5ca to your computer and use it in GitHub Desktop.
Save twoelevenjay/88c69ff8923428fa4a121fd8149dc5ca to your computer and use it in GitHub Desktop.
<?php
/*
* Sometimes you might find a WooCommerce shop ends up with products that
* have an attribute assigned but no terms selected for that attribute.
* I used this script to bulk delete any empty attribute from 117 products.
* In my case I was able to simply hook it to 'init', however when dealing
* with 500 plus products this may cause a timeout error. In these cases
* I would make this an AJAX function and create a JS script to handle multple
* requests in chunks.
*/
//add_action( 'init', 'remove_all_empty_atts' );
function remove_all_empty_atts() {
$products = get_posts(
array(
'post_type' => 'product',
'posts_per_page' => -1,
)
);
foreach ($products as $product) {
$new_attributes = $old_attributes = get_post_meta( $product->ID, '_product_attributes', true );
foreach ($old_attributes as $attribute => $values) {
$post_terms = wp_get_post_terms( $product->ID, $attribute );
if ( !is_wp_error( $post_terms ) ) {
if ( empty( $post_terms ) ) {
unset($new_attributes[$attribute]);
}
}
}
update_post_meta( $product->ID, '_product_attributes', $new_attributes );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment