如何批量删除只有一个产品的WooCommerce类别

时间:2018-08-22 作者:Shawn W

我想批量删除只包含一定数量产品的WooCommerce产品类别,是否有提供此功能的挂钩?

2 个回复
最合适的回答,由SO网友:Shawn W 整理而成

我最终这样做了,这对我来说很好,我把额外的类别改为未分类,而不是删除。

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\');

SO网友:De Coder

我相信是这样的:

$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 ); } }

结束