【问题标题】:WooCommerce update all variations (programmatically)WooCommerce 更新所有变体(以编程方式)
【发布时间】:2020-05-23 03:29:13
【问题描述】:

我正在尝试在所有产品的每个变体下更新 WooCommerce 中的自定义字段。我得到了适用于简单产品的代码,但无法遍历变体并更新它们。我在 Stackoverflow 上尝试了几乎所有 WooCommerce 变体循环,但它们都返回错误或根本不起作用。任何建议将不胜感激。简单产品的functions.php中的当前代码。

add_action('init', 'bulk_update_post_meta_data');
    function bulk_update_post_meta_data() {
        $args = array(
        'posts_per_page' => -1,
        'post_type' => 'product',
        'suppress_filters' => true
        );

        $posts_array = get_posts( $args );

        foreach($posts_array as $post_array) {
        $Cogcost = get_post_meta( $post_array->ID, '_regular_price', true );

            update_post_meta($post_array->ID, '_wc_cog_cost', $Cogcost);
        }
    }

【问题讨论】:

    标签: php wordpress loops woocommerce e-commerce


    【解决方案1】:
    add_action( 'init', 'bulk_update_post_meta_data' );
    
    function bulk_update_post_meta_data() {
        $args = array(
            'posts_per_page'     => -1,
            'post_type'          => 'product_variation',
            'suppress_filters'   => true
        );
    
        $posts_array = get_posts( $args );
    
        foreach ( $posts_array as $post_array ) {
            $Cogcost = get_post_meta( $post_array->ID, '_regular_price', true );
    
            update_post_meta( $post_array->ID, '_wc_cog_cost', $Cogcost );
        }
    }
    

    这将获得所有变体。

    【讨论】:

    • 感谢您提供的信息,虽然这不起作用我也在多个领域和不同的网站上尝试过,但它没有更新变体。
    • 请检查 $posts_array 是否有数据库中的值
    • 我不相信它有任何价值。 product_variation post_type 是 product 的子项,所以不是必须先获取 product 再获取 product_variation 吗?
    • @therealdeal 变体在 wp_posts 表中的帖子类型中存储为 product_variation
    • 我终于弄明白了。我有一个插件覆盖了我拥有的功能,所以没有正确提取数据。在全新安装的 WP 中尝试它之后,它起作用了。感谢您的帮助。
    猜你喜欢
    • 2013-03-19
    • 2019-04-04
    • 2018-05-11
    • 2017-01-04
    • 2020-09-01
    • 2016-10-17
    • 2021-11-10
    • 2021-12-03
    • 2023-04-06
    相关资源
    最近更新 更多