I'm looking to store the results from a WP_query as a $variable and access it outside of the loop. I can only seem to get the first result.
It's is important the $book_data from the results can be accessed outside of the loop.
Code
$args = array(
'post_type' => 'books',
'paged' => $paged,
);
$wp_query = new WP_Query( $args);
$count = $wp_query->post_count;
while ($wp_query->have_posts()) : $wp_query->the_post();
$book_name = get_post_meta( get_the_ID(), 'book_name', true );
$book_author = get_post_meta( get_the_ID(), 'book_author', true );
$book_data = $book_name . ' - ' . $book_author . '<br />';
endwhile;
wp_reset_postdata();
// Access data outside of Loop
echo $book_data;
Current Result
The Stand - Steven King
Desired Result
The Stand - Steven King
War and Peace - Leo Tolstoy
Middlemarch - George Eliot
CodePudding user response:
You're basically overwriting your variable on iteration. You could either a) display the books in the loop, or if as you mentioned you want to use that data in multiple places, you can add to an array and display at your discretion.
// Create empty array for book data
$book_data = [];
$args = array(
'post_type' => 'books',
'paged' => $paged,
);
$wp_query = new WP_Query( $args);
$count = $wp_query->post_count;
while ($wp_query->have_posts()) : $wp_query->the_post();
$book_name = get_post_meta( get_the_ID(), 'book_name', true );
$book_author = get_post_meta( get_the_ID(), 'book_author', true );
// Add each book to the array
$book_data[] = $book_name . ' - ' . $book_author;
// can also just echo the above out with:
// echo $book_name . ' - ' . $book_author . '<br />';
endwhile;
wp_reset_postdata();
// Access data outside of Loop
foreach ($book_data as $book) {
echo $book . '</br>;
}