I am building a website, and I am using the WFCM plugin to use it as a marketplace.
I want to when a price is changed in a product, I want to also change to all the products with the same name.
So far I achieved to change the price of all products regardless of the name.
The latest code I used :
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);
}
}
}
It doesn’t work, it changes all products prices. I know I am close, but I need help.
2
Answers
Eventually i made a plugin with this code i used wpdb as @CBroe suggested if anyone has the same question in the future. It doesn't only check the names it checks for a specific name.
In WordPress
WP_Query
, the ‘post_title’ parameter doesn’t exist.But, since WordPress 6.2+, you can use the undocumented search parameter
search_columns
for ‘post_title’ column like:Or you can also use a
WC_Product_Query
like:Now, your provided code is not really updating the related products price, but their names.
To update the related product price, use the following code replacement instead:
It should work