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:
$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?
Try iterating over it like so:
Best bet is to use getJSON function in jQuery http://api.jquery.com/jquery.getjson/ and loops through like any other javascript variable.
eg.
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:
… and in the jQuery: