首页 文章

使用Woocommerce中的自定义字段值替换购物车项目的价格

提问于
浏览
2

在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');

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

任何帮助将不胜感激 .

1 回答

  • 0

    如果您在购物车中使用 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文件中 .

    现在它应该工作

相关问题