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条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据