获取所有同名产品以在 WooCommerce 中更改价格

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

我正在构建一个网站,并使用 WFCM 插件将其用作市场。 我想当产品的价格发生变化时,我也想更改所有同名的产品。 到目前为止,我实现了更改所有产品的价格,无论其名称如何。

我使用的最新代码:

add_action('save_post', 'update_prices_by_product_name', 10, 2);

function update_prices_by_product_name($post_id, $post) {
    if ($post->post_type === 'product') {

        $product_name = $post->post_title;
        $new_price = get_post_meta($post_id, '_regular_price', true);
        $related_products = get_posts(array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'exclude' => $post_id,
            'post_title' => $product_name,
        ));

        foreach ($related_products as $related_product) {
            $related_product_id = $related_product->ID;

            $update_data = array(
                'ID' => $related_product_id,
                'post_title' => $product_name,
            );
            wp_update_post($update_data);
        }
    }
}

它不起作用,它改变了所有产品的价格。我知道我已经很接近了,但我需要帮助。

php wordpress woocommerce product marketplace
1个回答
0
投票

在 WordPress

WP_Query
中,'post_title' 参数不存在。

但是,从 WordPress 6.2+ 开始,您可以对 'post_title'

 列使用未记录的搜索参数 
search_columns,例如:

$related_products = get_posts( array(
    'post_type'      => 'product',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'exclude'        => $post_id,
    'search_columns' => array('post_title'),
    's'              => $product_name,
));

现在应该可以按照您的预期工作了。

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