Woocommerce: Get some custom cart item data value from a plugin

I am trying to get a specific value from from a product in the cart. I need this value as a multiplier for setting a price in a specific category, I have most of this working, except I am having issues fetching this value, which I set by a plugin called uni-cpo.

From the var_dump (cropped)

["_cpo_nov"]  =>   array(1) {
    array(2) {
       ["display_name"] => string(8) "stof_sqm"
       ["value"] => float(4) 2000

I need the float value 2000 fetched, but I am having trouble navigating the array.

add_action( 'woocommerce_before_cart', 'get_sqm', 99);
function get_sqm($length){
     global $woocommerce;
     $length = 0;
     foreach ($woocommerce->cart->cart_contents as $cart_item) {
         $item_id = $cart_item['6299'];
         if (isset($cart_item['data']->uni_nov_cpo_stof_sqm->uni_nov_cpo_stof_sqm->value)) {
             $length = $cart_item['data']->uni_nov_cpo_stof_sqm->uni_nov_cpo_stof_sqm->value;
     echo '<span class="hello">hello' . $length . '</span>';
    //Debug, comment to disable
    if (current_user_can('administrator') ) {
        echo '<pre>';
                var_dump( $cart_item );
        echo '</pre>';
    } //Debug end
     return $length;

I no I am on the right track, for some part of my code, but way off on navigating the array. If anyone could help out, point me in the right direction, or apply a solution, I would be forever grateful. Been struggling for weeks, getting to this point. Learning is very painful! 🙂


Based on your cropped var_dump, to get the desired value (2000), try the following revisited code:

add_action( 'woocommerce_before_cart', 'get_sqm', 99 );
function get_sqm() {
     $targeted_id = 6299;
     $length = 0;
     foreach (WC()->cart->get_cart() as $cart_item) {
         $product_id = $cart_item['product_id'];

         if ( isset( $cart_item['_cpo_nov']['uni_nov_cpo_stof_sqm']['value'] ) ) {
             $length = $cart_item['_cpo_nov']['uni_nov_cpo_stof_sqm']['value'];

             echo '<span class="hello">hello' . $length . '</span>';
     // return $length; // Not needed in an action hook

Code goes in functions.php file of the active child theme (or active theme). It should work.

Leave a Reply

Your email address will not be published. Required fields are marked *