使用 SQL 查询更改 Woocommerce 产品类别名称

问题描述 投票:0回答:1


我想在 Wordpress 中更新许多产品类别名称,从 csv 文件中检索它们。
csv 文件头只是:(ID;Product_category_Name)
我有 900 个类别和子类别,采用层次结构。
是否可以通过 ID 在数据库中搜索类别并更新类别名称?
这会保持层次结构正确吗?
我可以在名称中包含 UTF-8 中的“ö”、“ä”或“å”等字符吗? 我可以使用 wp php 函数或直接 sql 命令。

php mysql woocommerce product custom-taxonomy
1个回答
2
投票

您可以使用以下SQL查询(之前做好数据库备份):

    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'

您需要更换的地方:

  • new_name
    您的新产品类别名称
  • new_slug
    由您的新产品类别代号(小写字母和“
    -
    ”替换空格)
  • old_name
    您的旧产品类别名称(您要替换的)

您还可以使用以下函数进行相同的 SQL 查询:

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!.");
}

代码位于活动子主题(或活动主题)的 function.php 文件中。

用法 (假设您将“服装”产品类别重命名为“服装”):

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

会显示产品类别是否已重命名。已测试并有效。

© www.soinside.com 2019 - 2024. All rights reserved.