Zaka G
Zaka G

Reputation: 9

Change Woocommerce product category name with a SQL query


I want to update in Wordpress, many product_category names,retrieving them from a csv file.
the csv file header is just: (ID;Product_category_Name)
I have 900 categories and subcategories, in hierarchical structure.
is it possible to search in the DB for a category by ID and update the category name ?
will that keep the hierarchical structure correct ?
can i include in the names some chars like 'ö' 'ä' or 'å' in UTF-8? I can use wp php functions or direct sql commands.

Upvotes: -1

Views: 2565

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253824

This answer, answers your question title, but not all other questions.

You can use the following SQL query (making a database backup before):

    UPDATE wp_terms as a
    JOIN wp_term_taxonomy b ON a.term_id = b.term_id
    SET a.name = 'new_name', 
        a.slug = 'new_slug'
    WHERE b.taxonomy = 'product_cat'
    AND a.name = 'old_name'

Where you will need to replace:

  • new_name by your new product category name
  • new_slug by your new product category slug (in lowercase and "-" replace white spaces)
  • old_name by your Old product category name (the one you want to replace)

You can also use the following function with the same SQL query:

function rename_product_category( $old_name, $new_name ){
    global $wpdb;

    // Check that the new name doesn't exist
    if( term_exists( $new_name, 'product_cat' ) )
        return __("Your new product category term name already exist");

    // Check that the old name exist
    if( ! term_exists( $old_name, 'product_cat' ) )
        return __("Your old product category term name doesn't exist");

    $new_slug = sanitize_title( $new_name );

    $result = $wpdb->query("
        UPDATE {$wpdb->prefix}terms as a
        JOIN {$wpdb->prefix}term_taxonomy b ON a.term_id = b.term_id
        SET a.name = '$new_name',
            a.slug = '$new_slug'
        WHERE b.taxonomy = 'product_cat'
        AND a.name = '$old_name'
    ");

     if($result)
        return sprintf(
            __("The product category %s has been renamed to %s."),
            '"<strong>' . $old_name . '</strong>"',
            '"<strong>' . $new_name . '</strong>"'
        );
    else
        return __("Something is wrong!.");
}

Code goes in functions.php file of your child theme (or in a plugin).

USAGE (Let's say that you rename "Clothing" product category to "Wear"):

echo rename_product_category( 'Clothing', 'Wear' );

It will display if the product category has been renamed or not. Tested and works.

Upvotes: 2

Related Questions