4

I am having a search result page for custom post type. I want to have a ajax sorting feature. Eg sort the post by taxonomy without reloading the page. A very basic example will help. Thanks enter image description here

The Search Form :

<form id="cptsearch" action="/" method="get">
    <input type="text" name="s" />
    <input type="hidden" name="post_type" value="lat" />
    <input id="searchsubmit" type="submit" alt="Search" value="Search" />
</form>

Template Chooser :

function template_chooser($template) {
    global $wp_query;
    $post_type = get_query_var('post_type');
    if( $wp_query->is_search && $post_type == 'lat' ) {
    return locate_template('page_lat.php');
    }
    return $template;
}
add_filter('template_include', 'template_chooser');

This is the output template page_lat.php :

Search Results (Currently only prints title and post type :

if($_GET['s'] && !empty($_GET['s'])){

  $text =$_GET['s'];
}
 ?>


 <div class="container">

      <?php
        $args = array(
          'post_per_page'=> -1,
          's'=>$text
        );

        $query= new WP_Query($args);
        while($query->have_posts()): $query->the_post();
      ?>

      <div>
        <h5><?php the_title(); ?></h5>
        <strong>
          <?php echo get_post_type(); ?>
        </strong>
      </div>
    <?php endwhile; wp_reset_query(); ?>
  </div>
  • 3
    A very basic example would be quite in depth! Which part are you struggling with? It might be possible to break this question into many multiple questions, e.g. "How do I fetch posts via AJAX?", "How do I sort items on a page with Javascript?" or "How do I list taxonomies on a page?" or "How do I implement a toggle in javascript?". Additionally, are the posts already on the page and it's just sorting them? Or do you need to fetch them? Aka is clicking the search button going to load a new page where you can sort them? Or will it search in realtime? – Tom J Nowell Sep 5 '18 at 20:54
1
+100

So This is long question so giving you a simple example that will work fo Step 1) Cat1 cat2 cat3 for this first you need to call custom taxonomy in a form

Step 2) Assume you have cat1 cat2 as an checkbox with value of custom taxonomy id

Step 3) Add a click event

Step 4) Call your ajax function

Goto this example - http://www.tinyjewelbox.com/product-category/jewelry/ - I hope you wanted to achieve this click on checkboxes are custom taxonomy and on click of filter sorting according to taxonomy.

Method - lets start : -

This is the output template page_lat.php :

Search Results (Currently only prints title and post type :

            <?php 
            if($_GET['s'] && !empty($_GET['s'])){
              $text =$_GET['s'];
              $posttype = $_GET['post_type'];

            }
            else{
                $posttype = 'custom_post_type';
            }
            ?>
            //This will fetch your custom taxonomy cat1, cat2 , cat3

            <form action="" method="" class="" id="filter-menu" >
            <?php 
            $terms = get_terms('post_tag',, array('hide_empty' => false) );
            foreach($terms as $filteroption)
            {
                <input type="checkbox"  name="filter[]" value="<?php echo $filteroption->term_id; ?>" onclick="filtermenu()" >  
                <?php echo $filteroption->name; ?>
            }
            <input type="hidden" name="posttype" id="posttype" value="<?php echo $posttype; ?>" />
            ?>
            <form>
             <div class="container">
                 <div class="load_html">

                      <?php
                        $args = array(
                          'post_per_page'=> -1,
                          's'=>$text
                        );

                        $query= new WP_Query($args);
                        while($query->have_posts()): $query->the_post();
                      ?>

                      <div>
                        <h5><?php the_title(); ?></h5>
                        <strong>
                          <?php echo get_post_type(); ?>
                        </strong>
                      </div>
                    <?php endwhile; wp_reset_query(); ?>
                  </div>
              </div>

Add click event on click

                <script> //this a click event of checkbox which call ajax action
            function filtermenu(paged)
            {   
            var filtercheckedbox = // get your checkbox value via jquery; 
            var posttype = // get your posttype value; jQuery('#posttype').val(0);
            jQuery.ajax({
                url: AJAXURL,
                data: {
                    'action' : 'filter_menu' ,
                    'checkbox': filtercheckedbox, 
                    'posttype' :posttype,
                    'paged' : 1, 
                },
                type: 'POST',
                success: function(data) {
                        jQuery(".load_html").html(data);    
                }
            });     

            }   
            </script>

Add your action into functions.php

            <?php 
            // add this function to functions.php this is your ajax action 
            add_action( 'wp_ajax_filter_menu', 'wp_ajax_filter_menu' );
            add_action( 'wp_ajax_nopriv_filter_menu', 'wp_ajax_filter_menu' );

            function wp_ajax_filter_menu()
            {
            global $post, $wp_query;

            $args = array(
                'post_type' => '$_POST['post_type']',
                'tax_query' => array(
                                'relation' => 'AND',
                                 array(
                                    'taxonomy' => 'custom_taxonomy name',
                                    'field'    => 'term_id',
                                    'terms'    => array($_POST['checkbox']),
                                 ),
                ),
                'orderby'   => 'ASC',                   
            );

                $filteroption = new WP_Query( $args );
                if ( $filteroption->have_posts() ) :
                while ($filteroption->have_posts()) : $filteroption->the_post();
                  ?>

                  <div>
                    <h5><?php the_title(); ?></h5>

                  </div>
                <?php 
                endwhile; 
                else: 
                    return false; 
                endif;
            }   
            die;
            }
            ?>
1

Try to look into this a bit more:

get terms:

$type   = get_terms( array('type') );

Fetch all your taxonomies:

foreach ($type as $t) {
        if(!in_array($t->term_id, $type)){
                    echo '<label class="filter '.$t->slug.'">';
                    echo '<input type="checkbox" data-filter=".'. $t->term_id .'" class="filter-check '. $t->term_id .'" value="'. $t->term_id .'" name="type[]" ><div class="filter-title">'. $t->name .'</div>';
                    echo '</label>';
        }
}

look into your custom post type

if( !empty( $_POST['options_type'] ) ){
    array_push($args['tax_query'],   array(
              'taxonomy' => 'type',
              'field'    => 'term_id',
              'terms'    => $_POST['options_type'],
            )
          );
   }

in js file execute your ajax call

$("input:checkbox").on( "change", function() {

            var options_type = Array();
$( 'input[name="type[]"]:checked' ).each(function( index, value ) {
          options_type.push( $(this).val() );
            });

  jQuery.ajax({
            url : filters.ajax_filter,
            type : 'post',
            data : {
                action : 'filter_reports',
                options_type : options_type,

} });

1

do it with xmlhttp request

<button type="button" onclick="loadDoc()">Sort Type X</button>
<div id="result"></div>
<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("result").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "//example.com/s.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("search=XXX&sort=YYY");
}
</script>

in s.php

    <?php
        $xxx = $_POST['search'];
        $yyyy = $_POST['sort'];
        $args = array( //your query
        );
        while ( have_posts() ): the_post();
        // display post
        if ( have_posts() ): // If this is the last post, the loop will start over
                // Do something if this isn't the last post
        endif;
endwhile;
        ?>
-1

Just add orderby and/or order to your args. For example...

    $args = array(
      'post_per_page'=> -1,
      's'=>$text,
      'orderby' => 'title',
      'order'   => 'DESC',
    );

Here is more info

  • Thanks for A.. But the ajax part is missing.above args will only do a fixed result, I want it to be able to changed via Ajax – Latheesh V M Villa Sep 10 '18 at 15:31
  • Take a look at this example, this is a pretty basic example. If you don't want to code it I recommend FacetWP, Ive use this several times for more advanced filtering – RiddleMeThis Sep 10 '18 at 16:54
  • Thanks .it is some thing similar i want but how can i modify the search form and pass search term as ajax variable? – Latheesh V M Villa Sep 10 '18 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.