Skip to content

Instantly share code, notes, and snippets.

@imran-khan1
Created July 12, 2019 07:39
Show Gist options
  • Save imran-khan1/53ea4fe6fd8782f837bd7889f7627a2b to your computer and use it in GitHub Desktop.
Save imran-khan1/53ea4fe6fd8782f837bd7889f7627a2b to your computer and use it in GitHub Desktop.
<?php
/*
*Add WooCommerce checkout Custom shipping field
*/
add_filter( 'woocommerce_checkout_fields' , 'ci_custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function ci_custom_override_checkout_fields( $fields ) {
$fields['shipping']['shipping_fax'] = array(
'label' => __('Fax', 'woocommerce'),
'placeholder' => _x('fax', 'placeholder', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'ci_custom_checkout_field_process');
function ci_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['shipping_fax'] )
wc_add_notice( __( 'Please enter shipping fax.' ), 'error' );
}
/**
* Update the order meta with field value
*/
add_action( 'woocommerce_checkout_update_order_meta', 'ci_custom_checkout_field_update_order_meta' );
function ci_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['shipping_fax'] ) ) {
update_post_meta( $order_id, 'My Fax Field', sanitize_text_field( $_POST['shipping_fax'] ) );
}
}
/**
* Display field value on the admin order edit page
*/
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'ci_custom_checkout_field_display_admin_order_meta', 10, 1 );
function ci_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('Custom Fax Shipping Field').':</strong> ' . get_post_meta( $order->id, 'Custom Fax Field', true ) . '</p>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment