Search code examples
phpwordpresswoocommercecartcheckout

WooCommerce: Get $cart_item in price function


I'm using a custom function to change the style of the product price.

This is my actual function:

add_filter( 'woocommerce_format_sale_price', function( $price, $regular_price, $sale_price ) {
    // stuff happens here
}, 10, 3 );

It works fine on product detail pages if I want some meta fields from the product.

I can get these meta fields if I use global $product and go from there.

The problem is, that global $product throws an error if used on the cart/checkout page.

So I'm using is_product() and is_cart() to check where I am.

But I couldn't figure out how to get the meta fields from a product in the cart.

I know, that I could use $cart_item like $product. But it seems that there is no way to use that with global.

Is there any other way to get the cart item in the function above?


Solution

  • You can use WC()->cart to get cart object. then you can loop it using $cart->get_cart() to get cart_item. try below code.

    add_filter( 'woocommerce_format_sale_price', function( $price, $regular_price, $sale_price ) {
        if ( WC()->cart ) {
            $cart = WC()->cart; // Get cart
            if ( ! $cart->is_empty() ) {
                foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
                    $product_id = $cart_item['product_id'];
                    // stuff happens here
                }
            }
        }
    }, 10, 3 );