Skip to content

Instantly share code, notes, and snippets.

@eto4detak
Created October 19, 2018 10:47
Show Gist options
  • Save eto4detak/8369dfe9b80a90990605474c1c9f3664 to your computer and use it in GitHub Desktop.
Save eto4detak/8369dfe9b80a90990605474c1c9f3664 to your computer and use it in GitHub Desktop.
woo add field to cart
<?php
// add_action('woocommerce_before_add_to_cart_button','wdm_add_custom_fields');
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',10,3);
add_filter('woocommerce_get_item_data','wdm_add_item_meta',10,2);
add_action( 'woocommerce_checkout_create_order_line_item', 'wdm_add_custom_order_line_item_meta',10,4 );
function wdm_add_custom_fields()
{
global $product;
ob_start();
?>
<div class="wdm-custom-fields">
<input type="text" name="wdm_name">
</div>
<div class="clear"></div>
<?php
$content = ob_get_contents();
ob_end_flush();
return $content;
}
function wdm_add_item_data($cart_item_data, $product_id, $variation_id)
{
if(isset($_REQUEST['wdm_name']))
{
$cart_item_data['wdm_name'] = sanitize_text_field($_REQUEST['wdm_name']);
}
return $cart_item_data;
}
function wdm_add_item_meta($item_data, $cart_item)
{
if(array_key_exists('wdm_name', $cart_item))
{
$custom_details = $cart_item['wdm_name'];
$item_data[] = array(
'key' => 'Name',
'value' => $custom_details
);
}
return $item_data;
}
function wdm_add_custom_order_line_item_meta($item, $cart_item_key, $values, $order)
{
if(array_key_exists('wdm_name', $values))
{
$item->add_meta_data('_wdm_name',$values['wdm_name']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment