我希望將 WP_query 的結果存盤為 $variable 并在回圈之外訪問它。我似乎只能得到第一個結果。
可以在回圈之外訪問結果中的 $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 );
$book_data = $book_name . ' - ' . $book_author . '<br />';
endwhile;
wp_reset_postdata();
// Access data outside of Loop
echo $book_data;
當前結果
The Stand - 史蒂文·金
預期結果
立場 - 史蒂文·金
戰爭與和平 - 列夫·托爾斯泰
米德爾馬契 - 喬治·艾略特
uj5u.com熱心網友回復:
您基本上是在迭代時覆寫變數。您可以 a) 在回圈中顯示書籍,或者如果您提到要在多個地方使用該資料,您可以 b) 添加到陣列并自行決定顯示。
// 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>;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/358713.html
標籤:php WordPress的 循环
