A
A
alexiusgrey2022-02-08 15:58:20
WordPress
alexiusgrey, 2022-02-08 15:58:20

How to correctly call the value of the product meta field in the cart?

I need to be able to substitute a different price for a certain amount of goods.
From 50 pieces so that the price is prescribed differently. I want to take the value of this new price from my added numeric meta field.

There is a snippet that does a very similar thing - changing the cost of a product from the required number of pieces, but with a percentage discount. Works great.

add_action( 'woocommerce_before_calculate_totals', 'phpsof_quantity_based_pricing', 9999 );
 
function phpsof_quantity_based_pricing( $cart ) {
 
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;
 
    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;  
    
 
    // Define discount rules and thresholds
    $threshold1 = 50; // Change price if items > 50
    $discount1 = 0.05; // Reduce unit price by 5%
    $threshold2 = 100; // Change price if items > 100
    $discount2 = 0.1; // Reduce unit price by 10%
 
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
      if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 ) {
         $price = round( $cart_item['data']->get_price() * ( 1 - $discount1), 2 );
         $cart_item['data']->set_price( $price );
      } elseif ( $cart_item['quantity'] >= $threshold2 ) {
         $price = round( $cart_item['data']->get_price() * ( 1 - $discount2 ), 2 );
         $cart_item['data']->set_price( $price );
      }    
    }    
 }

I wanted to try replacing round( $cart_item['data']->get_price() * ( 1 - $discount1), 2 ) with my meta field $cart_item['data']->get_meta( '_opt_price', true )
This is a meta field for the product, but in the cart you need to refer not to $product, but to $cart_item['data'], but that didn't work.
How to correctly access the product meta-field from the cart?

First of all, I thought that somehow I added the meta field incorrectly, but compared with the numeric pls existing in the admin panel, such as _stock, $cart_item['data']->get_meta( '_stock', true ) didn't work either.

How to correctly call the value of the meta field?

I am very happy for those who use crack plugins and don't sweat it, but I would really like to deal with the meta field.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question