Create AJAX WooCommerce customer search box

/**
 * Creates AJAX WooCommerce customer search box.
 *
 * @see https://wpcodebook.com/create-ajax-woocommerce-customer-search-box/
 */
function wpcodebook_customer_search_ajax( $option_name, $user_id = false ) {

	echo '<select' .
			' name="' . esc_attr( $option_name ) . '"' .
			' class="wc-customer-search"' .
			' data-placeholder="' . esc_attr__( 'Search for a customer&hellip;' ) . '"' .
			' data-allow_clear="true"' .
		'>';

	if ( $user_id ) {

		$customer_label = ( ( $customer = new WC_Customer( $user_id ) ) && $customer->get_id() ?
			sprintf( __( '%1$s (#%2$s &ndash; %3$s)', 'woocommerce' ),
				$customer->get_first_name() . ' ' . $customer->get_last_name(),
				$customer->get_id(),
				$customer->get_email() ) :
			sprintf( __( 'Customer #%d' ), $user_id ) );

		echo '<option value="' . esc_attr( $user_id ) . '" selected>' . esc_html( $customer_label ) . '</option>';

	}

	echo '</select>';

}

You may also need to add your screen to WooCommerce screens.

Leave a Comment