Replace the price of the cart item with a custom field value in Woocommerce

岁酱吖の 提交于 2021-01-27 18:08:26

问题


In WooCommerce I am trying to replace the price of the cart items inwith a custom field price.

This is my code:

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

But it doesn't work. What I am doing wrong?

Any help will be appreciated.


回答1:


It doesn't work if you use get_the_ID() with get_post_meta() in cart. You should use instead:

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

Code goes in function.php file of your active child theme (or active theme).

Now it should work



来源:https://stackoverflow.com/questions/48375763/replace-the-price-of-the-cart-item-with-a-custom-field-value-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!