// Add custom fields to a specific selected shipping method
add_action( 'woocommerce_after_shipping_rate', 'carrier_custom_fields', 20, 2 );
function carrier_custom_fields( $method, $index ) {
if( ! is_checkout()) return; // Only on checkout page
//change this to the shipping method you are adding the custom field to
$customer_carrier_method = 'local_pickup:1';
if( $method->id != $customer_carrier_method ) return;
//get the selected shipping method
$chosen_method_id = WC()->session->chosen_shipping_methods[ $index ];
if($chosen_method_id == $customer_carrier_method ):
echo '<div class="custom-carrier">';
//create custom field
woocommerce_form_field( 'carrier_number' , array(
'type' => 'text',
'class' => array('form-row-wide carrier-number'),
'required' => true,
'placeholder' => 'FedEx Account Number',
), WC()->checkout->get_value( 'carrier_number' ));
echo '</div>';
endif;
}
// Check custom fields validation
add_action('woocommerce_checkout_process', 'carrier_checkout_process');
function carrier_checkout_process() {
if( isset( $_POST['carrier_number'] ) && empty( $_POST['carrier_number'] ) )
wc_add_notice( ( "Specify your FedEx account number." ), "error" );
}
// Save custom fields to order meta data
add_action( 'woocommerce_checkout_update_order_meta', 'carrier_update_order_meta', 30, 1 );
function carrier_update_order_meta( $order_id ) {
if( isset( $_POST['carrier_number'] ))
update_post_meta( $order_id, '_carrier_number', sanitize_text_field( $_POST['carrier_number'] ) );
}
// Add Customer FedEx Account Number to admin order data
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'misha_editable_order_meta_shipping' );
function misha_editable_order_meta_shipping( $order ){
$carrier_number = get_post_meta( $order->get_id(), '_carrier_number', true );
?>
<div class="address">
<p<?php if( empty($carrier_number) ) echo ' class="none_set"' ?>>
<strong>Customer FedEx Account Number:</strong>
<?php echo ( !empty( $carrier_number ) ) ? $carrier_number : 'Not specified' ?>
</p>
</div>
<div class="edit_address"><?php
woocommerce_wp_text_input( array(
'id' => 'carrier_number',
'label' => 'Customer FedEx Account Number',
'wrapper_class' => 'form-field-wide',
'class' => 'form-field form-field-wide carrier-number',
'style' => 'width:100%; padding: 0 8px',
'value' => $carrier_number,
'description' => 'This is the customer supplied FedEx account number to use for shipping.'
) );
?></div><?php
}
add_action( 'woocommerce_process_shop_order_meta', 'misha_save_shipping_details' );
function misha_save_shipping_details( $ord_id ){
update_post_meta( $ord_id, '_carrier_number', wc_clean( $_POST[ 'carrier_number' ] ) );
}