Pasar campos personalizados de producto al carrito de compra y al pedido en WC

Pasar campos personalizados de producto al carrito de compra y al pedido en WC

Pasar campos personalizados de producto al carrito de compra y al pedido en Woocommerce.

/**
* Add engraving text to cart item.
*
* @param array $cart_item_data
* @param int $product_id
* @param int $variation_id
*
* @return array
*/
function add_ebshipping_to_cart_item( $cart_item_data, $product_id, $variation_id ) {

$pen = get_post_meta( $product_id, "_ebshipping_peninsula", true );
$bal = get_post_meta( $product_id, "_ebshipping_baleares", true );

$cart_item_data["pen"] = $pen;
$cart_item_data["bal"] = $bal;

return $cart_item_data;
}
add_filter( "woocommerce_add_cart_item_data", "add_ebshipping_to_cart_item", 10, 3 );




/**
* Display engraving text in the cart.
*
* @param array $item_data
* @param array $cart_item
*
* @return array
*/
function display_ebshipping_text_cart( $item_data, $cart_item ) {
if ( empty( $cart_item["pen"] ) ) {
return $item_data;
}

$item_data[] = array(
"key" => __( "ebshipping", "pen" ),
"value" => wc_clean( $cart_item["pen"] ),
"display" => "",
);

if ( empty( $cart_item["bal"] ) ) {
return $item_data;
}

$item_data[] = array(
"key" => __( "ebshipping", "bal" ),
"value" => wc_clean( $cart_item["bal"] ),
"display" => "",
);

return $item_data;
}
//add_filter( "woocommerce_get_item_data", "display_ebshipping_text_cart", 10, 2 );




/**
* Add engraving text to order.
*
* @param WC_Order_Item_Product $item
* @param string $cart_item_key
* @param array $values
* @param WC_Order $order
*/
function add_ebshipping_to_order_items( $item, $cart_item_key, $values, $order ) {
if ( empty( $values["pen"] ) && empty( $values["bal"] )) {
return;
}

$item->add_meta_data( __( "ebshipping_pen", "pen" ), $values["pen"] );
$item->add_meta_data( __( "ebshipping_bal", "bal" ), $values["bal"] );
}
add_action( "woocommerce_checkout_create_order_line_item", "add_ebshipping_to_order_items", 10, 4 );




function checkout_update_refresh_shipping_methods( $post_data ) {
$packages = WC()->cart->get_shipping_packages();
foreach ($packages as $package_key => $package ) {
WC()->session->set( "shipping_for_package_" . $package_key, true ); // Or true
}
WC()->cart->calculate_shipping();
$packages = WC()->shipping->get_packages();

WC()->cart->calculate_totals();
}

add_action("woocommerce_checkout_update_order_review", "checkout_update_refresh_shipping_methods", 10, 1);