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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?