How to loop through a WordPress WP_Query object using jQuery?

I’m passing a WP_Query object to a success function in my JavaScript file and am having problems trying to loop through it.

My PHP:

Read More
$args = array(
    'post_type'  => 'post'
);
$query = new WP_Query( $args );

// Pass the $query object to the success function in my script.
echo json_encode( $query );

My success function in my script:

success: function( data ) {
    // I'd like to loop through the query object here.
},...

I know how to loop through a WP_Query object server-side:

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        echo get_the_title();
    }
}

But how can I loop through the query object using jQuery inside my success function in my script?

Related posts

Leave a Reply

3 comments

  1. I question whether you want the entire WP_Query object returned, or just the results of the query (the posts property). My suggested approach would be:

    $args = array(
        'post_type'  => 'post'
    );
    $query = new WP_Query( $args );
    
    // Pass the $query object to the success function in my script.
    echo json_encode( $query->posts );
    

    … and in the jQuery:

    success: function( data ) {
        for(var i in data) {
            var post = data[i];
            // Do something with post object here...
        }
    },...