Skip to content

Instantly share code, notes, and snippets.

@fervous
Last active June 9, 2017 17:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fervous/76aebbe57dba94229d4be1b2f57fc3f3 to your computer and use it in GitHub Desktop.
Save fervous/76aebbe57dba94229d4be1b2f57fc3f3 to your computer and use it in GitHub Desktop.
wc vendors pro.. add a custom message text field for customers on the product page
// Message or Custom Field for the Product Page for Customers to enter text.
// This should be added to your theme/child theme functions.php file
/* Creates Field after add to cart button */
function add_custom_info_field() {
echo '<table class="variations" cellspacing="0">
<tbody>
<tr>
<td class="label"><label for="custom"><span style="font-size:10px;color:#999;font-weight:400;">Message:</span></label></td>
<td class="value">
<input type="text" name="custom-info-message" size="30"value="" placeholder="Add a Message Here..." />
</td>
</tr>
</tbody>
</table>';
}
add_action( 'woocommerce_after_add_to_cart_button', 'add_custom_info_field' );
/* Saves field data */
function save_add_custom_info_field( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['custom-info-message'] ) ) {
$cart_item_data[ 'custom_info_message' ] = $_REQUEST['custom-info-message'];
/* below statement make sure every add to cart action as unique line item */
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
add_action( 'woocommerce_add_cart_item_data', 'save_add_custom_info_field', 10, 2 );
/* Renders field entry on cart and checkout */
function render_mssg_meta_on_cart_and_checkout( $cart_data, $cart_item = null ) {
$custom_items = array();
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['custom_info_message'] ) ) {
$custom_items[] = array( "name" => 'Custom Info or Message', "value" => $cart_item['custom_info_message'] );
}
return $custom_items;
}
add_filter( 'woocommerce_get_item_data', 'render_mssg_meta_on_cart_and_checkout', 10, 2 );
/* Renders field info onto orders pages and emails */
function custom_info_order_meta_handler( $item_id, $values, $cart_item_key ) {
if( isset( $values['custom_info_message'] ) ) {
wc_add_order_item_meta( $item_id, "custom_info_message", $values['custom_info_message'] );
}
}
add_action( 'woocommerce_add_order_item_meta', 'custom_info_order_meta_handler', 1, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment