Last active
April 25, 2021 10:27
-
-
Save doroness/35cd8734a430966f77b684d3dd7d6cfa to your computer and use it in GitHub Desktop.
Add Custom Data to WooCommerce Order via Custom Fields on Product Page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Based on this post https://wisdmlabs.com/blog/add-custom-data-woocommerce-order-2/ | |
* Add custom data to order from the product page to admin order page in | |
* See more useful snippets here -> https://wpuniverse.online/ | |
*/ | |
/** | |
* THE HOOKS | |
*/ | |
add_action('woocommerce_before_add_to_cart_button','wpu_add_custom_fields'); | |
add_filter('woocommerce_add_cart_item_data','wpu_add_item_data',10,3); | |
add_filter('woocommerce_get_item_data','wpu_add_item_meta'); | |
add_action( 'woocommerce_checkout_create_order_line_item', 'wpu_add_custom_order_line_item_meta'); | |
/** | |
* THE HANLERS | |
*/ | |
// This will output before the "add to cart" button, making it a part of the "add to cart" form so it needs to be a proper form field | |
// i.e select, text input, checkbox etc... | |
function wpu_add_custom_fields () { | |
// Do whatever you need here. e.g | |
echo <input type="text" name="your_custom_data_name" value="your_custom_data_value"> | |
} | |
// This will Add your custom data to the cart item | |
function wpu_add_item_data ($cart_item_data, $product_id, $variation_id) { | |
if(isset($_REQUEST['your_custom_data_name'])) { | |
$cart_item_data['your_custom_data_name'] = sanitize_text_field($_REQUEST['your_custom_data_name']); | |
} | |
//As this is a filter - we need to return | |
return $cart_item_data; | |
} | |
// This will display your custom meta in cart page | |
function wpu_add_item_meta ($item_data, $cart_item) { | |
if(array_key_exists('your_custom_data_name', $cart_item)) { | |
$custom_details = $cart_item['your_custom_data_name']; | |
$item_data[] = array( | |
'key' => 'Name', | |
'value' => $custom_details | |
); | |
} | |
return $item_data; | |
} | |
// Add Custom Details to Order Line Items | |
function wpu_add_custom_order_line_item_meta ($item, $cart_item_key, $values, $order) { | |
if(array_key_exists('your_custom_data_name', $values)) | |
{ | |
$item->add_meta_data('_custom_name',$values['your_custom_data_name']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment