WP_Query on custom taxonomy works fine but fails if run through wp_ajax_

I’m using WP_Query to collate some info about posts based on their custom taxonomy.
My arguments are as follows:

$args = array(
        'posts_per_page'=> -1,
        'post_status' => 'publish'
    );

    if ( isset($_POST['tag_id']) ) :
        $args['tax_query'] =
            array(array(
                'taxonomy' => 'region',
                'field' => 'id',
                'terms' => $_POST['tax_id'],
            ));
    endif;

Then I loop through and collate my data. And that works perfectly well. But because it’s quite a heavy query, and appears for each taxonomy id I thought I’d run it on user demand and return the data with wp_ajax_

Read More

The same query seems to ignore all the tax_query arguments when returned through ajax. The arguments are the same and the correct “terms” is being passed. It’s identical. I can’t figure it out. Is this a bug? It’s bugging me.

Updated to put the code in pastebin:
http://pastebin.com/rxSJ1C2n

The class is at the top, then the bit of jQuery I’ve put at the bottom but is actually in a separate file.

Related posts

Leave a Reply

1 comment

  1. I don’t see your call to the ajaxurl in your code. Are you actually getting an ajax response?

    Try this javascript:

    jQuery(document).ready( function($) {
        $("a.getviews").click( function() {
            var td = $(this).parent();
            /* only fetch results once */
            $(this).unbind('click').bind('click', function(){return false;});
            // replace button with loader
            $(td).html('<span class="loader"></span>');
    
            $.ajax({
                    type: 'POST',
                    url: ajaxurl,
                    data: { action: "get_views", tax_id: td.attr("id") },
                    success: function(response) {
                    $("td").html(response);
                    return false;                               
                }
    
                });
    
                });
        });
    

    With large ajax responses I always have better luck buffering the output.

    Add ob_start(); before your loop then at the end add:

    $response = ob_get_contents();
                    ob_end_clean();
    
                echo $response;
    
                    die(1);