Add manufacturer category to WooCommerce product from post title

I had to categorize more than 4000 WooCommerce products (car tyres) which contained manufacturer name as first word in title. So did it with the following code:

/**
 * Add manufacturer product category to WooCommerce product from post title
 *
 * @return void
 */
function pf_add_manufacturer_cat() {

    // Get manufacturer from product title
    for ($i = 1; $i < 6; $i++) {

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 1000,
            'page' => $i,
        );
        $products = new WP_Query( $args );
        while ( $products->have_posts() ) {
            $products->the_post();

            // First word of title is manufacturer
            $terms = explode( ' ', get_the_title() );

            // Append cat
            $term = term_exists( $terms[0], 'product_cat');
            if ( $term['term_id'] > 0 ) {
                wp_set_post_terms( get_the_ID(), $term['term_id'], 'product_cat', true );
            }
        }

    }

}
add_action( 'init', 'pf_add_manufacturer_cat' );

Documentation for the used function http://codex.wordpress.org/Function_Reference/wp_set_post_terms

Advertisements

Author: Michal Zuber

Full stack developer, biker and rollerblader. Owner and developer at https://nevilleweb.sk/ Co-founded http://neville.sk/ Blog at https://michalzuber.wordpress.com/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s