Skip to content

Instantly share code, notes, and snippets.

@tradesouthwest
Created January 7, 2018 20:32
Show Gist options
  • Select an option

  • Save tradesouthwest/dffd2a78bb5dd0416b19741f5c9f49ab to your computer and use it in GitHub Desktop.

Select an option

Save tradesouthwest/dffd2a78bb5dd0416b19741f5c9f49ab to your computer and use it in GitHub Desktop.

Revisions

  1. tradesouthwest created this gist Jan 7, 2018.
    71 changes: 71 additions & 0 deletions wp-search-filter-ajax.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@

    <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>
    <script>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;
    });
    });</script>
    <?php
    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');
    ?>