0

I would like to bulk delete WooCommerce product categories that only contain a certain number of products, is there a hook that provides this functionality?

0

Something like this, I believe:

$args = array( 'number' => -1, 'hide_empty' => false ); $product_categories = get_terms( 'product_cat', $args ); foreach( $product_categories as $cat ) { if ( $cat->count <=1 ) { wp_delete_term( $cat->term_id ); } }

0

I ended up doing it like this which worked well for me, I moved the extra categories to un-categorized instead of deleting.

function woo_cat_list() {
echo "<div style='color:red;'>";
$args = array(
    //'number' => -1,
    'hide_empty' => false
);
$limit = 10;
$uncategorized_category_id = 21;
$product_categories = get_terms( 'product_cat', $args );
$i=0;
foreach( $product_categories as $cat ) {
    if ( $cat->count <=$limit ) {               
            echo "<br />CATEGORY : ".$cat->name."<br /><br />";
            $args = array(
                'post_type'      => 'product',
                'posts_per_page' => -1,
                'product_cat'    => $cat->slug
            );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
                global $product;
                echo "<br />======> PRODUCT : ".get_the_title()." (Will move to uncategorized) <br /><br />";
                $id = get_the_id();
                $p = wc_get_product($id);
                $p->set_category_ids([ $uncategorized_category_id ] );
                $p->save(); // uncomment this to save 
            endwhile;               
            wp_reset_query();           
            wp_delete_term( $cat->term_id, 'product_cat' );
        $i++;
    }
}
echo "Total : ".$i; exit;
echo "</div>";
}           
add_shortcode('woo_product_cat_list', 'woo_cat_list');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.