<?php

  add_action( 'wp_footer', 'ajax_fetch' );
  function ajax_fetch() {
    if ( is_post_type_archive( 'downloads' ) ) {
  ?>
<script type="text/javascript">
function fetch() {

  jQuery.ajax({
    url: window.inoby_vars.ajax.url,
    type: 'post',
    data: {
      action: 'data_fetch',
      keyword: jQuery('#keyword').val(),
      pcat: jQuery('#cat').val()
    },
    success: function(data) {
      jQuery('#datafetch').html(data);
    },
  });

}
</script>
<?php
  }}

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
    if ($_POST['pcat']) {
        $product_cat_id = array(esc_attr( $_POST['pcat'] ));
    }else {
        $terms = get_terms( 'downloads-category' ); 
        $product_cat_id = wp_list_pluck( $terms, 'term_id' );
    }
    $the_query = new WP_Query( 
      array( 
        'posts_per_page' => -1, 
        's' => esc_attr( $_POST['keyword'] ), 
        'post_type' => array('downloads'),
        'tax_query' => array(
          array(
            'taxonomy'  => 'downloads-category',
            'field'     => 'term_id',
            'terms'     => $product_cat_id,
            'operator'  => 'IN',
          )
        )
      ) 
    );
    if( $the_query->have_posts() ) :
      echo '<div class="downloads-wrap">';
      while( $the_query->have_posts() ): 
        $the_query->the_post(); 
        get_template_part("post-types/downloads/parts/card");
      endwhile;
      echo '</div>';
      wp_reset_postdata();  
    else:
      echo '<div>'.__('Nenašli sa žiadne súbory na stiahnutie, skúste zopakovať vyhľadávanie s inými kľúčovými výrazmi','inoby').'</div>';
    endif;


    die();
}

?>