drdawt9210 2019-05-23 14:14
浏览 86
已采纳

基于自定义字段对特定产品的折扣

I want a discount 11% on specific products that have a published year after 2016 in my woocommerce eshop.

This field (pub_year) is a custom field in a custom table with the name fancyplugin_wc_product_info in the wpdb.

I tried some code(which is a mixed code from a research I made) with no success.

The code that I tried:

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; 
} 
  • 写回答

2条回答 默认 最新

  • dongtong0796 2019-05-23 16:43
    关注

    Your SQL query using WPDB class is incomplete and wrong… As the column for product ID in the table wp_fancyplugin_wc_product_info is post_id, you need to query it for the current product ID… Try the following instead:

    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;
    }
    

    Code goes in functions.php file of your active child theme (or active theme). It should work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向