This website uses cookies to personalize your experience. By using this website you agree to our cookie policy.

Reply To: If exact search for a product then automatically add to cart

Home Forums Product Support Forums Ajax Search Pro for WordPress Support If exact search for a product then automatically add to cart Reply To: If exact search for a product then automatically add to cart

#39228
Ernest MarcinkoErnest Marcinko
Keymaster

Hi,

I wish I could suggest a code snippet to this, but it is a bit more complicated.

I can however point you to the right direction of how I would start off. First, I would use the advanced content field to print some custom HTML with the EAN code. This HTML code can be used on the front-end to check if the product should be added.
Something like:
{descriptionfield}[<div class="ean_exists">{ean_code}</div>]

Then using the asp_search_end hook to check if that ean is in the results, an exactly only once:

add_action('wp_footer', 'asp_add_to_cart_handler', 999999);
function asp_add_to_cart_handler() {
	?>
	<script>
	let asp_add_to_cart_handler = function(e) {
		let id = e.detail[0],
		    instance = e.detail[1],
			phrase = e.detail[2],
			data = e.detail[3],
			results_with_ean = document.querySelectorAll( '.asp_r_' + id + '_' + instance + ' .ean_exists' );
		if ( results_with_ean.length == 1 ) {
			document.querySelectorAll( '.asp_r_' + id + '_' + instance + ' .button' ).click();
		}
	}
	document.querySelectorAll('.asp_m').forEach(function(node) {
		node.addEventListener('asp_search_end', asp_add_to_cart_handler);
	});
	</script>
	<?php
}

This does not handle enter key press etc.., but should be a very good start to a possible solution.