繁体   English   中英

无法从循环外的 WP_Query 访问结果

[英]Can't access results from WP_Query outside of Loop

我希望将 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 - 史蒂文·金
战争与和平——列夫·托尔斯泰
米德尔马契——乔治·艾略特

您基本上是在迭代时覆盖变量。 您可以 a) 在循环中显示书籍,或者如果您提到要在多个位置使用该数据,您可以添加到数组中并自行决定显示。

// 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>;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM