abdelhadi-h
11/12/2017 - 2:55 PM

HTML+AJAX +WORDPRESS

------------------------------------------------------------BEGIN html -----------------------------------------------------
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
    <?php
        if( $terms = get_terms( 'category', 'orderby=name' ) ) :
            echo '<select name="categoryfilter"><option>Select category...</option>';
            foreach ( $terms as $term ) :
                echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
            endforeach;
            echo '</select>';
        endif;
    ?>
    <label>
        <input type="radio" name="date" value="ASC" /> Date: Ascending
    </label>
    <label>
        <input type="radio" name="date" value="DESC" selected="selected" /> Date: Descending
    </label>
    <button>Apply filters</button>
    <input type="hidden" name="action" value="customfilter">
</form>
<div id="response"></div>
------------------------------------------------------------END html -----------------------------------------------------
-------------------------------------------------------------BEGIN AJAX---------------------------------------------------------
jQuery(function($){
    $('#filter').submit(function(){
        var filter = $('#filter');
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(), // form data
            type:filter.attr('method'), // POST
            beforeSend:function(xhr){
                filter.find('button').text('Applying Filters...');          },
            success:function(data){
                filter.find('button').text('Apply filters');                $('#response').html(data);
            }
        });
        return false;
    });
});
-------------------------------------------------------------END AJAX---------------------------------------------------------
-------------------------------------------------------------BEGIN WORDPRESS---------------------------------------------------------
function my_filters(){
    $args = array(
        'orderby' => 'date',
        'order' => $_POST['date']
    );
  
        if( isset( $_POST['categoryfilter'] ) )
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $_POST['categoryfilter']
            )
        );
   
    $query = new WP_Query( $args );
  
    if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();
            echo '<h2>' . $query->post->post_title . '</h2>';
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No posts found';
    endif;
  
    die();
}
  
  
add_action('wp_ajax_customfilter', 'my_filters');
add_action('wp_ajax_nopriv_customfilter', 'my_filters');

-------------------------------------------------------------END WORDPRESS---------------------------------------------------------