I’m developing a WordPress plugin with WooCommerce so the customer can add customizable dynamic products to their cart. In order to get the customized data into the cart, I have the following lines:
WC()->add_to_cart($product_id, $quantity, 0, [], [ "custom_data" => $custom_data ]);
Where $custom_data stores the customized information of the product (coordinates and dimensions basically).
This works properly.
When a customer actually buys the product, a new order is created and I can view it in my administrator panel from WooCommerce and I want the custom data to be displayed for every item on the order in order to then manufacture the item given the coordinates and dimensions, but I don’t want the customer to see these data at any point because it makes no sense. (The data is just a stringified JSON).
I’ve tried this:
function add_custom_data_to_order($item, $cart_item_key, $values, $order) {
if (isset($values["custom_data"]) {
$item->add_meta_data("custom_data", $values["custom_data"]);
}
}
add_action("woocommerce_checkout_create_order_line_item", "add_custom_data_to_order", 10, 4);
This works but it’s not what I’m trying to achieve since the data is shown to the user during checkout and it’s displayed on the admin order view for the item as a property of the item, not as extra information.
How can I achieve this?
2
Answers
You need to prepend an underscore to your metadata key, you can see that here:
This should hide it from the front-end for the user, then you can add the following filter and function to display it on the admin order page:
First, you have a mistake in
WC()->add_to_cart(
that should beWC()->cart->add_to_cart(
instead, if you want to add a product to cart. There is also a missing closing bracket)
in your function.You can hide custom order item metadata, from customer, in 2 different ways: