add custom field on checkout page woocommerce code example
Example 1: add custom field to variation woocommerce
add_action( 'woocommerce_variation_options_pricing', 'bbloomer_add_custom_field_to_variations', 10, 3 );
function bbloomer_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
woocommerce_wp_text_input( array(
'id' => 'custom_field[' . $loop . ']',
'class' => 'short',
'label' => __( 'Custom Field', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
)
);
}
add_action( 'woocommerce_save_product_variation', 'bbloomer_save_custom_field_variations', 10, 2 );
function bbloomer_save_custom_field_variations( $variation_id, $i ) {
$custom_field = $_POST['custom_field'][$i];
if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'custom_field', esc_attr( $custom_field ) );
}
add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );
function bbloomer_add_custom_field_variation_data( $variations ) {
$variations['custom_field'] = '<div class="woocommerce_custom_field">Custom Field: <span>' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</span></div>';
return $variations;
}
Example 2: Woocommerce Display Custom Field value on the Thank You page [Custom Field Display 2]
/**
* Display field value on the Thank You page..
*
* PHP Custom Feild Value
*
*
*/
add_action( 'woocommerce_thankyou', 'misha_view_order_and_thankyou_page', 20 );
add_action( 'woocommerce_view_order', 'misha_view_order_and_thankyou_page', 20 );
function misha_view_order_and_thankyou_page( $order_id ){ ?>
<h2>Location You Choose</h2>
<table class="woocommerce-table shop_table gift_info">
<tfoot>
<tr>
<th scope="row">Store Location</th>
<td><?php echo get_post_meta( $order_id, 'My Field', true ); ?></td>
</tr>
</tfoot>
</table>
<?php }