确定 WooCommerce 中的产品类型 - 致命错误:

我正面临这个问题。


致命错误:未捕获错误:在 null 上调用成员函数 is_type()


有人会在这方面帮助我吗?


这是我使用的代码。


add_action( 'woocommerce_before_calculate_totals', 'sione_change_cart_item_name_and_price', 10, 1 );

function sione_change_cart_item_name_and_price( $cart ) {

    global $product;

    

    // Get new items names from WC_Session

    $session_data = (array) WC()->session->get( 'new_item_names' );

    //$sku_data = (array) WC()->session->get( 'product_sku' );

    // Loop through cart items

    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        

        

        if($product->is_type( 'simple' )) {

            $item_names = $product->get_short_description();

        } else {

            $item_names = $cart_item['data']->get_name() .", ". $cart_item['data']->get_attribute('color'). "," . $cart_item['data']->get_attribute('gender') . " (Product SKU: " . $cart_item['data']->get_sku() . ")";

        }

        // If item name doesn't exist in WC_Session for this cart item, we do it

        if( ! isset($session_data[$cart_item_key]) ) {

            $session_data[$cart_item_key] = $item_names;

            WC()->session->set( 'new_item_names', $session_data );

        }

    }

}

任何帮助将不胜感激。谢谢


慕妹3242003
浏览 55回答 1
1回答

慕森王

您可以通过以下方式确定产品类型function sione_change_cart_item_name_and_price( $cart ) {&nbsp; &nbsp; if ( is_admin() && ! defined( 'DOING_AJAX' ) )&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )&nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; // Loop through cart items&nbsp; &nbsp; foreach ( $cart->get_cart() as $cart_item ) {&nbsp; &nbsp; &nbsp; &nbsp; // Get an instance of the WC_Product object&nbsp; &nbsp; &nbsp; &nbsp; $product = $cart_item['data'];&nbsp; &nbsp; &nbsp; &nbsp; // Get product id&nbsp; &nbsp; &nbsp; &nbsp; $product_id = $cart_item['product_id'];&nbsp; &nbsp; &nbsp; &nbsp; if( $product->is_type( 'simple' )) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo 'Simple = ' . $product_id . '<br>';&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo 'Else = ' . $product_id . '<br>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}add_action( 'woocommerce_before_calculate_totals', 'sione_change_cart_item_name_and_price', 10, 1 );
打开App,查看更多内容
随时随地看视频慕课网APP