【发布时间】:2016-09-13 05:06:42
【问题描述】:
我想在 WooCommerce 中将所有产品价格提高一定百分比。
可能会使用挂钩(例如:正常价格 100 美元 + 10%= 110 美元)简单且可变的产品。
我想将所有简单和可变产品的价格提高到正常价格的 10%。
如何提高价格?
谢谢
【问题讨论】:
标签: php wordpress woocommerce cart product
我想在 WooCommerce 中将所有产品价格提高一定百分比。
可能会使用挂钩(例如:正常价格 100 美元 + 10%= 110 美元)简单且可变的产品。
我想将所有简单和可变产品的价格提高到正常价格的 10%。
如何提高价格?
谢谢
【问题讨论】:
标签: php wordpress woocommerce cart product
有两种情况
案例 1 - 所有产品(按百分比批量提高产品价格)
此自定义函数将按照您可以在此代码 sn-p 末尾设置的百分比更新所有产品价格。这将只进行一次。
所有产品价格、正常价格和促销价都会更新……
如果您以后需要再次执行此操作,请参阅此 sn-p 代码(如下)之后的过程。
此脚本仅适用于登录的管理员用户。
function bulk_update_product_prices($percent=0){
if(get_option( 'wc_bulk_updated_prices' ) != 'yes' && is_admin() ) {
// prevent updating prices more than once
add_option( 'wc_bulk_updated_prices' );
$args = array(
// WC product post types
'post_type' => array('product', 'product_variation'),
// all posts
'numberposts' => -1,
'post_status' => 'publish',
);
if($percent == 0) return;
echo 'bla bla';
$percent = 1 . '.' . $percent;
$shop_products = get_posts( $args );
foreach( $shop_products as $item){
$meta_data = get_post_meta($item->ID);
if (!empty($meta_data['_regular_price'])) {
$regular_price = $meta_data['_regular_price'][0] * $percent;
update_post_meta($item->ID, '_regular_price', $regular_price);
}
if (!empty($meta_data['_sale_price'])) {
$sale_price = $meta_data['_sale_price'][0] * $percent;
update_post_meta($item->ID, '_sale_price', $sale_price);
}
if (!empty($meta_data['_price'])) {
$price = $meta_data['_price'][0] * $percent;
update_post_meta($item->ID, '_price', $price);
}
}
// Once done an option is set to yes to prevent multiple updates.
update_option( 'wc_bulk_updated_prices', 'yes');
}
}
// set your percentage (if you want 20%, so you put 20)
bulk_update_product_prices(20); // <== == == == == == Here set your percent value
此代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。
现在,浏览您网站的页面(以管理员身份登录)。你完成了。
之后您可以删除此代码。
如果您需要再次使用此脚本,则需要执行这 4 个步骤。在上面的代码sn-p中:
第 1 步 - 重置安全选项 - 替换:
// set your percentage (here the percentage is 20%, so we put 20) bulk_update_product_prices(20);通过这个:
// Do it again later (Resetting the script) update_option( 'wc_bulk_updated_prices', 'no');第 2 步 - 浏览您网站的页面(以管理员身份登录):
第 3 步 - 替换回这个:
// Do it again later (Resetting the script) update_option( 'wc_bulk_updated_prices', 'no');通过这个:
// set your percentage (here the percentage is 20%, so we put 20) bulk_update_product_prices(20);第 4 步 - **更新价格 - 浏览您网站的页面(以管理员身份登录)
此代码已经过测试并且可以工作。
案例 2 - 购物车(提高购物车商品价格)
您可以使用 woocommerce_before_calculate_totals 挂钩来自定义您的购物车商品价格。
在下面的代码中,我为购物车中的每件商品添加 10%。
这适用于所有类型的产品。
这是代码:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_percentage', 10 );
function add_custom_percentage( $cart_object ) {
// set your percent (here 10 is 10%)
$percent = 10;
foreach ( $cart_object->cart_contents as $item ) {
$item['data']->price *= 1 . '.' . $percent;
}
}
此代码已经过测试并且可以运行。
这个代码自然会出现在您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。
参考文献:
【讨论】: