[英]Update all WooCommerce products if “sale_price” is greater than “price”
I am trying to update wp_postmeta table for all products sale price. 我正在尝试更新所有产品销售价格的wp_postmeta表。
I'm struggling with how to work this, due to both fields being meta_key
/ meta_value
pairs in this wp_postmeta table. 我正在努力解决这个问题,因为这个字段在这个wp_postmeta表中都是meta_key
/ meta_value
对。
How can I write a query that will update all '_sale_price' = 0 WHERE '_sale_price' > '_price'
? 如何编写将更新所有'_sale_price' = 0 WHERE '_sale_price' > '_price'
?
A different approach with a custom function that should do the same job. 使用自定义函数的不同方法应该执行相同的工作。 You will have to use this function just one time , and then remove it after the job is done (at first site load, the process will depend on number of products you have). 您只需使用此功能一次 ,然后在作业完成后将其删除(首次加载站点时,该过程将取决于您拥有的产品数量)。
Here is the code: 这是代码:
function update_products_sale_price(){
$args = array(
'posts_per_page' => -1,
'post_type' => 'product',
'post_status' => 'publish'
);
// getting all products
$products = get_posts( $args );
// Going through all products
foreach ( $products as $key => $value ) {
// the product ID
$product_id = $value->ID;
// Getting the product sale price
$sale_price = get_post_meta($product_id, '_sale_price', true);
// if product sale price is not defined we give to the variable a 0 value
if (empty($sale_price))
$sale_price = 0;
// Getting the product sale price
$price = get_post_meta($product_id, '_price', true);
// udate sale_price to 0 if sale price is bigger than price
if ($sale_price > $price)
update_post_meta($product_id, '_sale_price', '0');
}
}
// Here the function we will do the job.
update_products_sale_price();
You can also embed the code function in a hook… 您还可以将代码函数嵌入到钩子中...
This code goes on function.php file of your active child theme or theme 此代码位于活动子主题或主题的function.php文件中
This code is tested and fully functional 此代码经过测试且功能齐全
References: 参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.