Woocommerce:从插件中获取一些自定义购物车项目数据值

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

我正在尝试从购物车中的产品中获取特定值。 我需要这个值作为在特定类别中设置价格的乘数,我已经完成了大部分工作,除了我在获取这个值时遇到问题,这是我通过一个名为 uni-cpo 的插件设置的。

来自 var_dump(裁剪)

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

我需要获取浮点值 2000,但我在导航数组时遇到问题。

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

我不,对于我的某些代码,我走在正确的轨道上,但在导航数组时偏离了方向。如果有人可以提供帮助,为我指明正确的方向,或应用解决方案,我将永远感激不已。苦苦挣扎了数周,才走到这一步。学习很痛苦! :)

根据您裁剪后的 var_dump,要获得所需的值 (2000),请尝试重新访问以下代码:

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>';
             break;
         }
     }
     // return $length; // Not needed in an action hook
 }

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该可以工作。