"How Did You Hear About Us?" Checkout Field
Adds a dropdown to the classic checkout asking customers how they found your store, saves the answer with the order and shows it on the order screen.
Opens WPIDE on
Code
$wpide_referral_options = array(
'' => 'Choose an option',
'search' => 'Search engine',
'social' => 'Social media',
'friend' => 'Friend or family',
'ad' => 'Advertisement',
'other' => 'Other',
);
add_action( 'woocommerce_after_order_notes', function ( $checkout ) use ( $wpide_referral_options ) {
woocommerce_form_field( 'wpide_referral_source', array(
'type' => 'select',
'label' => 'How did you hear about us?',
'required' => false,
'class' => array( 'form-row-wide' ),
'options' => $wpide_referral_options,
), $checkout ? $checkout->get_value( 'wpide_referral_source' ) : '' );
} );
add_action( 'woocommerce_checkout_create_order', function ( $order ) use ( $wpide_referral_options ) {
$value = isset( $_POST['wpide_referral_source'] ) ? sanitize_key( wp_unslash( $_POST['wpide_referral_source'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
if ( '' !== $value && isset( $wpide_referral_options[ $value ] ) ) {
$order->update_meta_data( '_wpide_referral_source', $wpide_referral_options[ $value ] );
}
} );
add_action( 'woocommerce_admin_order_data_after_billing_address', function ( $order ) {
$source = $order->get_meta( '_wpide_referral_source' );
if ( $source ) {
echo '<p><strong>Heard about us via:</strong> ' . esc_html( $source ) . '</p>';
}
} );
Notes
Edit $options to change the choices. Answers are stored in the order meta key _wpide_referral_source.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.