尝试在插件中使用 foreach 访问购物车项目,但在管理 wordpress 中编辑和设置页面时出现严重错误

问题描述

我正在使用 Dokan-woocommerce-wordpress。 尝试使用插件文件中的 foreach 访问添加到购物车中的商品的供应商 ID。

// Get vendor UPI ID and Murchant Code
        global $woocommerce;
        $items = $woocommerce->cart->get_cart();
         
        foreach( $items as $my_cart_item ){
            $my_product_id = $my_cart_item['product_id'];
        }
        
        
        $vendor_id = get_post_field( 'post_author',$my_product_id );
        $store_details = get_user_Meta($vendor_id,'dokan_profile_settings');
        $upi_id = $store_details[0]['vendor_upi_id'];
        $murchant_code = $store_details[0]['vendor_upi_murchant_code'];

上面的代码提供了所需的输出,但此处的某些内容导致了严重错误,并且“编辑”页面无法在 wordpress 管理中打开。

enter image description here

这是错误日志消息

PHP Warning:  Invalid argument supplied for foreach() in /home3/cardocte/public_html/shreeroyals.com/wp-content/plugins/upi-qr-code-payment-for-woocommerce/includes/payment.PHP on line 57

请提出任何解决方案。

解决方法

我找到了解决方案。如果 get_cart() 在管理区域中执行,它似乎会导致问题,因此将上述代码段封装在条件中:if( ! is_admin() ) { } 为我解决了该问题。