Last active
November 3, 2021 16:41
-
-
Save jmarreros/5367a583dd82a7dc8079754525231e9e to your computer and use it in GitHub Desktop.
Add custom text field attribute WooCommerce
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
<?php | |
// show custom field in product page | |
function dcms_display_field() { | |
// Optional validation for specif category | |
// global $product; | |
// $categories = $product->get_category_ids(); | |
// if ( ! in_array(34, $categories )) return; | |
echo '<div class="custom-field-wrapper"> | |
<label for="title-field">Ingresa algún texto:</label> | |
<input type="text" id="dcms-custom-field" name="dcms-custom-field" value=""> | |
</div><br /><hr />'; | |
} | |
add_action( 'woocommerce_before_add_to_cart_button', 'dcms_display_field', 10, 0 ); | |
// Validate custom field | |
function dcms_field_validation( $passed, $product_id, $quantity ) { | |
if( isset( $_REQUEST['dcms-custom-field'] ) && empty($_REQUEST['dcms-custom-field'])) { | |
$passed = false; | |
wc_add_notice( 'Ingresa algún texto personalizado', 'error' ); | |
} | |
return $passed; | |
} | |
add_filter( 'woocommerce_add_to_cart_validation', 'dcms_field_validation', 10, 3 ); | |
// Add field data to the cart | |
function dcms_add_field_to_cart( $cart_item_data, $product_id, $variation_id ) { | |
if( ! empty( $_REQUEST['dcms-custom-field'] ) ) { | |
$cart_item_data['dcms-custom-field'] = sanitize_text_field($_REQUEST['dcms-custom-field']); | |
} | |
return $cart_item_data; | |
} | |
add_filter( 'woocommerce_add_cart_item_data', 'dcms_add_field_to_cart', 10, 3 ); | |
// Display field in the cart | |
function dcms_display_field_to_cart( $item_name, $cart_item, $cart_item_key ) { | |
if ( isset($cart_item['dcms-custom-field']) ){ | |
$item_name .= sprintf("<p>Texto: %s </p>", $cart_item['dcms-custom-field']); | |
} | |
return $item_name; | |
} | |
add_filter( 'woocommerce_cart_item_name', 'dcms_display_field_to_cart', 10, 3 ); | |
// Add custom field to order | |
function dcms_add_field_to_order( $item, $cart_item_key, $values, $order ) { | |
if ( isset( $values['dcms-custom-field'] )){ | |
$item->add_meta_data( 'Texto', $values['dcms-custom-field'], true ); | |
} | |
} | |
add_action( 'woocommerce_checkout_create_order_line_item', 'dcms_add_field_to_order', 10, 4 ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment