【问题标题】:Replace the price of the cart item with a custom field value in Woocommerce用 Woocommerce 中的自定义字段值替换购物车项目的价格
【发布时间】:2018-01-22 06:29:41
【问题描述】:

在 WooCommerce 中,我试图用自定义字段价格替换购物车商品的价格。

这是我的代码:

function custom_cart_items_price ( $cart_object ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    foreach ( $cart_object->get_cart() as $cart_item ) {

        // get the product id (or the variation id)
        $id = $cart_item['data']->get_id();

        // GET THE NEW PRICE (code to be replace by yours)
        $new_price = (int)get_post_meta( get_the_ID(), '_c_price_field', true ); // <== Add your code HERE

        // Updated cart item price
        $cart_item['data']->set_price( $new_price ); 
    }
}

add_filter( 'woocommerce_before_calculate_totals', 'custom_cart_items_price');

但它不起作用。我做错了什么?

任何帮助将不胜感激。

【问题讨论】:

    标签: php wordpress woocommerce cart price


    【解决方案1】:

    如果您在购物车中使用get_the_ID()get_post_meta(),它不起作用。你应该改用:

    add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_price');
    function custom_cart_items_price ( $cart ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
             return;
    
        if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
            return;
    
        foreach ( $cart->get_cart() as $cart_item ) {
    
             // get the product id (or the variation id)
             $product_id = $cart_item['data']->get_id();
    
             // GET THE NEW PRICE (code to be replace by yours)
             $new_price = get_post_meta( $product_id, '_c_price_field', true ); 
    
             // Updated cart item price
             $cart_item['data']->set_price( floatval( $new_price ) ); 
        }
    }
    

    代码进入您的活动子主题(或活动主题)的 function.php 文件中。

    现在应该可以了

    【讨论】:

    • 非常感谢!我确实意识到我使用了错误的 ID。感谢您的帮助,让我重回正轨。
    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 2019-02-17
    • 2019-12-21
    • 1970-01-01
    • 2017-10-09
    • 2015-11-28
    • 1970-01-01
    相关资源
    最近更新 更多