Using get_meta values foreach product discount on cart page in WooCommerce

Viewed 85

Trying to get the discounted price foreach product using this meta key discounted_price which i'm using on specific products.

I added a custom field meta box on the single edit product screen to add a different discount price foreach product.

It works for the first product on the cart page but not the others. I assume i need to add foreach in there somewhere but not sure how.

add_filter( 'woocommerce_cart_item_name', 'append_custom_label_to_item_name', 20, 3 );
function append_custom_label_to_item_name( $product_name, $cart_item, $cart_item_key ){

    if ( isset($cart_item['pricing']['discounted']) && $cart_item['data']->get_price() != $cart_item['pricing']['discounted'] ) {
    
        $discounted_price = (float) $cart_item['pricing']['discounted'];
        $default_price    = (float) $cart_item['pricing']['active'];
        $quantity         = (int)   $cart_item['quantity'];

        // Calculate new product price
        $new_price = ($default_price + ($discounted_price * ($quantity - 1))) / $quantity;

        // Get the discount percentage (if needed)
        $percent = 100 - ($new_price / $default_price * 100);
        
        $id = $cart_item['product_id'];
        
        $product = wc_get_product( $id );
        $price = $product->get_meta( 'discounted_price' );

        $product_name .= ' <em>( ' . __('$', 'twentytwenty') . $price . ' discount )</em>';
        
    }
    return $product_name;
}

$price only works for the first product in the cart

0 Answers
Related