phpwordpresspluginswoocommercecategories

Bulk relink child categories to parent categories on Woocommerce


We recently imported a large product store from Big commerce to woocommerce but have run into an issue regarding the categories.

The products are links to the child category only, meaning if you visit the parent category no products are being shown.

Product linked to child category but not parent

Is there a way to have all child categories relink to the parent category on a large scale? the store has 6000+ products and hundreds of categories so even with bulk editing tools it would take a long time to accomplish this task.

Thank you in advance and apologies if this has already been asked, hard to find the correct wording for this situation.

** I came across this code**

add_action('save_post', 'assign_parent_terms', 10, 2);

function assign_parent_terms($post_id, $post){

    if($post->post_type != 'product')
        return $post_id;

    // get all assigned terms   
    $terms = wp_get_post_terms($post_id, 'product_cat' );
    foreach($terms as $term){
        while($term->parent != 0 && !has_term( $term->parent, 'product_cat', $post )){
            // move upward until we get to 0 level terms
            wp_set_post_terms($post_id, array($term->parent), 'product_cat', true);
            $term = get_term($term->parent, 'product_cat');
        }
    }

}

Could someone point in the right direction of tweaking the code so that I don't have to save each product individually but rather run it once to update them all?

Again thank you for your help.


Solution

  • Don't do the add_action() part. Use

    $products = get_posts(['post_type' => 'product', 'posts_per_page' => 100, 'offset' => 0]);
    var_dump(count($products));
    foreach ($products as $product) {
        assign_parent_terms($oroduct->ID, $product);
    }
    

    Refresh page. Increase offset manually with 100 after every refresh until the dump shows 0.