简体   繁体   中英

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.

This answer, answers your question title, but not all other questions (see how to ask ) .

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 function.php file of your active child theme (or active theme).

USAGE (Let's say tha 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM