【问题标题】:Change Woocommerce product category name with a SQL query使用 SQL 查询更改 Woocommerce 产品类别名称
【发布时间】:2019-04-27 20:52:17
【问题描述】:


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

【问题讨论】:

  • 您不能在 StackOverFlow 中同时提出多个问题。规则是一问一答。

标签: php mysql woocommerce product custom-taxonomy


【解决方案1】:

此答案回答了您的问题标题,但不是所有其他问题(请参阅how to ask

您可以使用以下 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 由您的新产品类别 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' );

如果产品类别已被重命名,它将显示。经过测试并且可以工作。

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多