Create AJAX WooCommerce product search box

/**
 * Creates AJAX WooCommerce product search box.
 *
 * @see https://wpcodebook.com/create-ajax-woocommerce-product-search-box/
 * @see https://github.com/woocommerce/woocommerce/blob/8.0.3/plugins/woocommerce/includes/class-wc-ajax.php
 * @see https://github.com/woocommerce/woocommerce/blob/8.0.3/plugins/woocommerce/client/legacy/js/admin/wc-enhanced-select.js
 */
function wpcodebook_product_search_ajax( $option_name, $product_id = false ) {

	/**
	 * Alternative values for the `data-action` attribute:
	 * `woocommerce_json_search_products`, `woocommerce_json_search_downloadable_products_and_variations`
	 *
	 * Additional attribute examples:
	 * `data-display_stock="true"`
	 * `data-exclude_type="variable"`
	 * `data-exclude="123"` (post ID)
	 * `data-sortable="true"`
	 */
	echo '<select' .
			' name="' . esc_attr( $option_name ) . '"' .
			' class="wc-product-search"' .
			' data-placeholder="' . esc_attr__( 'Search for a product&hellip;', 'woocommerce' ) . '"' .
			' data-allow_clear="true"' .
			' data-action="woocommerce_json_search_products_and_variations"' .
		'>';

	if ( $product_id ) {
		$product_label = ( ( $product = wc_get_product( $product_id ) ) ?
			wp_strip_all_tags( $product->get_formatted_name() ) :
			sprintf( __( 'Product #%d' ), $product_id ) );
		echo '<option value="' . esc_attr( $product_id ) . '" selected>' . esc_html( $product_label ) . '</option>';
	}

	echo '</select>';

}

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

Leave a Comment