Last active
April 13, 2024 15:07
-
-
Save stacklast/3384934d405f2f0bd7cd826251f8707f to your computer and use it in GitHub Desktop.
Add custom field into Woocomerce Checkout
This file contains hidden or 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
| /* | |
| * ADD DNI as new field to the CHECKOUT page WooCommerce | |
| * https://www.businessbloomer.com/woocommerce-visual-hook-guide-checkout-page/ Checkout Layout Hooks map. | |
| * */ | |
| //Add custom field to the checkout page | |
| add_action( 'woocommerce_before_checkout_billing_form', 'agrega_mi_campo_personalizado' ); | |
| function agrega_mi_campo_personalizado( $checkout ) { | |
| //echo '<div id="additional_checkout_field"><h2>' . __('Información adicional') . '</h2>'; | |
| woocommerce_form_field( 'dni', array( | |
| 'type' => 'text', | |
| 'class' => array('my-field-class form-row-wide'), | |
| 'label' => __('Identificación'), | |
| 'required' => true, | |
| 'placeholder' => __('Introduce el Nº de Cédula o RUC'), | |
| ), $checkout->get_value( 'dni' )); | |
| echo '</div>'; | |
| } | |
| /** | |
| * Validate on submit Checkout Process | |
| */ | |
| add_action('woocommerce_checkout_process', 'comprobar_campo_dni'); | |
| function comprobar_campo_dni() { | |
| //Comprueba si se ha introducido un valor y si está vacío se muestra un error. | |
| if ( !$_POST['dni'] ) | |
| wc_add_notice( __( 'Cédula o RUC, es un campo requerido. Debe de introducir su DNI para finalizar la compra.' ), 'error' ); | |
| } | |
| /** | |
| * Update the value given in custom field | |
| */ | |
| add_action( 'woocommerce_checkout_update_order_meta', 'actualizar_info_pedido_con_nuevo_campo' ); | |
| function actualizar_info_pedido_con_nuevo_campo( $order_id ) { | |
| if ( !empty( $_POST['dni'] ) ) { | |
| update_post_meta( $order_id, 'DNI', sanitize_text_field( $_POST['dni'] ) ); | |
| } | |
| } | |
| /** | |
| * Show the value | |
| */ | |
| add_action( 'woocommerce_admin_order_data_after_billing_address', 'mostrar_campo_personalizado_en_admin_pedido', 10, 1 ); | |
| function mostrar_campo_personalizado_en_admin_pedido($order){ | |
| echo '<p><strong>'.__('DNI').':</strong> ' . get_post_meta( $order->id, 'DNI', true ) . '</p>'; | |
| } | |
| /** | |
| * Add the value to the order email | |
| */ | |
| add_filter('woocommerce_email_order_meta_keys', 'muestra_campo_personalizado_email'); | |
| function muestra_campo_personalizado_email( $keys ) { | |
| $keys[] = 'DNI'; | |
| return $keys; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment