Right now I'm submitting a drop-down form to it's own page (action="") to filter posts displayed.

I'd like to not have to refresh the page, which resets the forms. Is there a way to query posts/filter them using ajax?


I'd go with @Vinicius' answer with the following changes:

  1. Change type: 'GET' to type: 'POST'

  2. Change ajax: 1 to action: 'filter_posts'

  3. Replace add_action('init', 'check_ajax'); with:

    add_action('wp_ajax_filter_posts', 'check_ajax'); add_action('wp_ajax_nopriv_filter_posts', 'check_ajax');

  4. Remove:

    if (!isset($_POST['ajax'])) return false;


Yes, but you'd have to work on it a little bit. Assume you're sending the following variables via jQuery:

    type: 'GET',
    url: location.href,
    data: {
        ajax: 1,
        category_id: <some_id>
    success: function(data){

Then, you would verify the request like:

add_action('init', 'check_ajax');
function check_ajax() {

    if (!isset($_POST['ajax']))
        return false;

    $query = new WP_Query( 'cat=' . intval($_POST['category']) );
    while( $query->have_posts() ) {
        <div class="<?php post_class(); ?>">
            <h2> ... <?php the_title(); ?> ... </h2>
            ... your post template


It's far from complete and it's not tested, but I hope it gives you some direction. =D

  • the URL: location.href, should that be set to /wp-admin/ajax.php? I've been scouring tutorials to try and understand ajax in wordpress but can't seem to figure it out. And is there more code involved than this? I'm pretty clueless right now
    – marctain
    Jul 27 '12 at 5:37
  • You're probably getting how ajax work on the admin interface. If you need ajax in your theme, then you have to catch the request in your theme. Take my code and @kalengi's observations. Jul 27 '12 at 11:02
  • I did. Sorry guys, I'm a little newbier than this when it comes to ajax. I put the first code in a document.ready(function... in a JS file. Then I put the next code in my functions.php. IS this the general idea? I even set up a brand new test template to try this out. No luck.
    – marctain
    Jul 27 '12 at 15:35

Did you manage to load the filtered page without AJAX ?

If you are modifying the main query using new WP_Query, you can use this kind of request parameter


where the query-parameter can be taxonomy term, author or any other parameter.

For the JavaScript (JQuery), you can simply use

$('#target-div').load(targetPage + ' #target-div-content', function() {
    // do script here

where targetPage is the request parameter.

Hope this help

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.