Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Woocommerce Cash On Delivery Add Custom Field

How can I add a custom textarea field right below cah on delivery so when you click on the cash on delivery radio button a textarea appears to enter details that get saved into the order?

like image 205
sebas Avatar asked Sep 29 '16 14:09

sebas


1 Answers

  1. Copy checkout/payment-method.php file to your theme directory woocommerce folder. i.e your-theme/woocommerce/checkout/payment-method.php

  2. change the content li tag with the following code:

<li class="wc_payment_method payment_method_<?php echo $gateway->id; ?>">
<input id="payment_method_<?php echo $gateway->id; ?>" type="radio" class="input-radio" name="payment_method" value="<?php echo esc_attr( $gateway->id ); ?>" <?php checked( $gateway->chosen, true ); ?> data-order_button_text="<?php echo esc_attr( $gateway->order_button_text ); ?>" />
<label for="payment_method_<?php echo $gateway->id; ?>">
<?php echo $gateway->get_title(); ?> <?php echo $gateway->get_icon(); ?>
</label>
<?php if ( ( $gateway->has_fields() || $gateway->get_description() ) &&  $gateway->id != "cod" ) : ?>
<div class="payment_box payment_method_<?php echo $gateway->id; ?>" <?php if ( ! $gateway->chosen ) : ?>style="display:none;"<?php endif; ?>>
<?php $gateway->payment_fields(); ?>
</div>
<?php endif; ?>
<?php if ( $gateway->id == "cod" ) : ?>
<div class="payment_box payment_method_<?php echo $gateway->id; ?>" <?php if ( ! $gateway->chosen ) : ?>style="display:none;"<?php endif; ?>>
<?php $gateway->payment_fields(); ?>
<label>Custom Field</label>
<input type="text" name='cod_custom_field'>
</div>
<?php endif; ?>
</li>

  1. Add following code in yout themes functions.php file

/**
 * Update the order meta with field value
 */
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

function my_custom_checkout_field_update_order_meta( $order_id ) {
    if ( ! empty( $_POST['cod_custom_field'] ) ) {
        update_post_meta( $order_id, 'COD Custom Field', sanitize_text_field( $_POST['cod_custom_field'] ) );
    }
}

/**
 * Display field value on the order edit page
 */
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );

function my_custom_checkout_field_display_admin_order_meta($order){
    echo '<p><strong>'.__('COD Custom Field').':</strong> ' . get_post_meta( $order->id, 'COD Custom Field', true ) . '</p>';
}

That's it. Hope this help.

like image 162
Jimmy Avatar answered Oct 12 '22 19:10

Jimmy