我希望在2016年后在我的woocommerce eshop中发布的特定产品有11%的折扣。
此字段(pub_year)是定制表中的自定义字段,在wpdb中的名称为fancyplugin_wc_product_info。
我尝试了一些代码(这是我所做的研究中的混合代码),但没有成功。
我尝试的代码如下:
function get_price_multiplier() {
return 100; // 100 the multiplier
}
function get_price_discount() {
return 11; // 11% discount
}
add_filter('woocommerce_product_get_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_get_sale_price', 'custom_price', 99, 2 );
function custom_price( $price, $product ) {
global $woocommerce, $post, $wpdb;
$table_name = $wpdb->prefix . 'fancyplugin_wc_product_info';
$result = ("SELECT * FROM {$table_name} WHERE pub_year >= '2016'");
if( $result ) {
$price = $price - (get_price_discount() / get_price_multiplier() * $price);
}
return $price;
} 发布于 2019-05-24 00:43:48
使用WPDB类的SQL查询不完整且…错误。由于表wp_fancyplugin_wc_product_info中的产品ID列为post_id,因此需要查询当前产品ID…请尝试执行以下操作:
function process_sale_price( $price ) {
$percentage = 11; // 11% discount
return ( 100 - $percentage ) / 100 * $price;
}
add_filter('woocommerce_product_get_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_get_sale_price', 'custom_price', 99, 2 );
function custom_price( $price, $product ) {
global $wpdb;
$result = $wpdb->get_var( $wpdb->prepare("
SELECT post_id FROM {$wpdb->prefix}fancyplugin_wc_product_info
WHERE pub_year >= '2016' AND post_id = %d
", $product->get_id() ) );
if( ! empty($result) ) {
return process_sale_price( $price );
}
return $price;
}代码放在活动子主题(或活动主题)的functions.php文件中。应该能行得通。
发布于 2019-05-23 22:29:53
如果我是你,我会做一个程序来更新2016年后发布的每个注册表,直到最终日期范围,因为如果你只从2016年开始使用它,你将更新所有产品。
例:从2016到2017年。
为什么我要构建一个过程,而不是只在数据库中执行更新?
也许在将来,你需要做同样的事情,然后你已经有了这样做的过程。
为了安全起见,你可以做一个备份表格,在那里你可以保存新旧产品的价格。因为如果你需要回滚价格,你可以在哪里得到它!
https://stackoverflow.com/questions/56277201
复制相似问题