M
M
makboriska2021-11-12 23:07:36
AJAX
makboriska, 2021-11-12 23:07:36

Ajax search for subcategories in woocommerce, how to run a loop?

I’m learning to make a website, I just took the “Vouchers” niche, selling promotional codes, there is a search on the site, I want to do an ajax search for subcategories, not goods (woocommerce), namely subcategories, let’s say I have a subcategory “mastercard”, I drive in the name of this subcategory and get the result, now the search on the site works by records (ajax itself works), I need a handler that would display subcategories instead of posts, tell me where to dig because there is nothing at all about this on the Internet, below is the code that is:

jQuery(document).ready(function($){
  $('.search-input').keypress(function(eventObject){
    var searchTerm = $(this).val();
    // проверим, если в поле ввода более 2 символов, запускаем ajax
    if(searchTerm.length > 2){
      $.ajax({
        url : '/wp-admin/admin-ajax.php',
        type: 'POST',
        data:{
          'action':'codyshop_ajax_search',
          'term'  :searchTerm
        },  
        success:function(result){
                    $('.codyshop-ajax-search').addClass("activesearch");
          $('.codyshop-ajax-search').fadeIn().html(result);
        }
      });
    }
  });
});


the code below is a handler that displays posts, but I need subcategories (with pictures) of woocommerce products (since a subcategory is a voucher and a product is a face value, so I need to search for subcategories
<?php
if ( ! defined( 'ABSPATH' ) ) {
  exit; // Exit if accessed directly
}

// ajax поиск по сайту
add_action( 'wp_ajax_nopriv_codyshop_ajax_search', 'codyshop_ajax_search' );
add_action( 'wp_ajax_codyshop_ajax_search', 'codyshop_ajax_search' );
function codyshop_ajax_search(){ 
  $args = array( 
    'post_type'      => 'any', 
    'post_status'    => 'publish', 
    'order'          => 'DESC', 
    'orderby'        => 'date', 
    's'              => $_POST['term'], 
    'posts_per_page' => 5 
  ); 
  $query = new WP_Query( $args ); 
  if($query->have_posts()){ 
  while ($query->have_posts()) { $query->the_post();?> 
<li>    
  <?php if(!empty($codyshop_url)) {
    the_post_thumbnail('codyshop-mini-thumbnail');
  } else{ ?>
    <span><img src="<?php echo esc_url(get_template_directory_uri().'/assets/images/default-mini.gif'); ?>" alt=""></span>
  <?php } ?>
  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
  <?php the_excerpt();?>
 </li> 
<?php } }else{ ?>
  <li><a href="#">Ничего не найдено, попробуйте другой запрос</a></li>
<?php } exit;
}


Thanks in advance!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question