Home > Net >  how to display own data only for a non-variant product in WooCommerce
how to display own data only for a non-variant product in WooCommerce

Time:11-15

I'm trying to display some custom data in the cart for non-variant products using the woocommerce_get_item_data hook. Even though I have the condition set, I still have a problem with the variant products giving me an error.

My code:

add_filter( 'woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2 );
function display_cart_item_custom_meta_data( $item_data, $cart_item ) {
    
    if ( empty($cart_item["variation"])) {
    
            $my_data = $cart_item["my_data"];
            $data_array = array();
        
    $data_array[] = array(
                    'key'       => "Some Key",
                    'value'       => "Some Value",
                );
    
return $data_array;
        
        }
}

Variant error:

Warning: Invalid argument supplied for foreach() in /data/0/b/0b142c6f-d1fc-41f2-b82d-95dd95505032/xxx.sk/sub/shop/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 3741

Warning: count(): Parameter must be an array or an object that implements Countable in /data/0/b/0b142c6f-d1fc-41f2-b82d-95dd95505032/xxx.sk/sub/shop/wp-content/plugins/woocommerce/includes/wc-template-functions.php on line 3752

where is the problem, please?

CodePudding user response:

add_filter('woocommerce_get_item_data', 'display_cart_item_custom_meta_data', 10, 2);

function display_cart_item_custom_meta_data($item_data, $cart_item) {

    if (empty($cart_item["variation"])) {

        $my_data = $cart_item["my_data"];
        $data_array = array();

        $data_array[] = array(
            'key' => "Some Key",
            'value' => "Some Value",
        );

        return $data_array;
    }
    return $item_data;
}

You should always return the data, otherwise, it will throw the error.

  • Related