【发布时间】:2021-12-27 18:29:44
【问题描述】:
我希望将 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 - 史蒂文·金
期望的结果
The Stand - 史蒂文·金
战争与和平 - 列夫·托尔斯泰
Middlemarch - 乔治艾略特
【问题讨论】: