【问题标题】:Can't access results from WP_Query outside of Loop无法访问循环外 WP_Query 的结果
【发布时间】: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 - 乔治艾略特

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    您基本上是在迭代时覆盖您的变量。您可以 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>;
        }
    

    【讨论】:

    • 感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 2020-08-24
    • 1970-01-01
    • 2020-04-04
    • 2018-05-12
    相关资源
    最近更新 更多