Search product tags

Add js

$('body').on('click', '.searchform button.ux-search-submit.submit-button', function(e) {
		e.preventDefault();
		var search = $("input.search-field").val();
		$.ajax({
		  	type: 'post',
            url: '/wp-admin/admin-ajax.php',
            data: {
                action: 'check_category_search',
                search: search, 
            },
            success: function (response) {
				if(response.data.result && response.data.result == 'category'){
					window.location.href = response.data.url_search;
				}
				else{
					$("input.search-field").val(search);
					$('.searchform').submit();
				}
            }
        });
		
	});

Add function


<?php
// Search Check Category 
add_action('wp_ajax_check_category_search', 'tzn_check_category_search');
add_action('wp_ajax_nopriv_check_category_search', 'tzn_check_category_search');
function tzn_check_category_search()
{
	$result = "no_category";
	$url_search = "";
	if (isset($_POST['search']) && $_POST['search'] != "") {
		$search = $_POST['search'];
		$terms = get_terms(array('taxonomy' => 'product_tag', 'hide_empty' => false));
		if (!empty($terms)) {
			foreach ($terms as $term) {
				//if(str_contains($term->slug, $search) || str_contains($term->name, $search) ||  $term->name == $search ||  $term->slug == $search){
				if (strtolower($term->name) == strtolower($search) ||  $term->slug == strtolower($search)) {
					$result = "category";
					// $url_search = site_url('?swoof=1&product_cat=' . $term->slug);
					$url_search = site_url('/' . $term->slug);
				}
			}
		}
	}
	wp_send_json_success(['result' => $result, 'url_search' => $url_search]);
}

Leave a Reply

Your email address will not be published. Required fields are marked *