繁体   English   中英

我应该放置 wp_reset_postdata(); 结束后; 或结束; ?

[英]Should I place wp_reset_postdata(); after endwhile; or endif; ?

我花了一些时间阅读WordPress Codex,以及各种主题,可以看到一些开发人员插入了<?php wp_reset_postdata(); ?> <?php wp_reset_postdata(); ?>endif; 在博客循环中,而其他人则在endwhile;之间插入代码endwhile; 和结束endif; 的博客循环。 我已经尝试了这两个位置,但还没有看到差异。 有正确的位置吗?

这个函数应该重置你运行的第二个查询..函数the_post允许你使用你可以在循环中运行的所有函数,比如the_title() the_content等等..

所以你重置the_post函数并在endwhile; 你已经可以重置了。 如果您愿意,也可以在if语句中使用您的主要查询。

<?php
// this is the main query check if there is posts
if ( have_posts() ) : 
    // loop the main query post and run the_post() function on each post that you can use the function the_title() and so on..
    while ( have_posts() ) : the_post(); 
        the_title(); // title of the main query

        // the is second query
        $args = array( 'posts_per_page' => 3 );
        $the_query = new WP_Query( $args );
        // check if there is a posts in the second query
        if ( $the_query->have_posts() ) :
            // run the_post on the second query now you can use the functions..
            while ( $the_query->have_posts() ) : $the_query->the_post();
                the_title();
                the_excerpt();
            endwhile;

            // reset the second query
            wp_reset_postdata();

            /* here we can use the main query function already if we want..
            its in case that you want to do something only if the second query have posts.
            You can run here third query too and so on...
            */

            the_title(); // title of the main query for example

        endif;

    endwhile;
endif;
?>

wp_reset_postdata()仅在您有辅助循环(您在页面上运行其他查询wp_reset_postdata()时才需要。 该函数的目的是将全局 post 变量恢复回主查询中的当前 post。

例子:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    OUTPUT MAIN POSTS HERE

<?php endwhile; endif; ?>

在上面的代码中,我只是使用主循环来显示帖子。 没有理由包含wp_reset_postdata() 全局 post 变量正是它应该的样子。

如果我决定在页面上的其他地方添加辅助循环,那么我将需要wp_reset_postdata()

// This query is just an example. It works but isn't particularly useful.
$secondary_query = new WP_Query( array(
    'post_type' => 'page'
) );

if ( $secondary_query->have_posts() ) :

    // Separating if and while to make answer clearer.
    while ( $secondary_query->have_posts() ) : $secondary_query->the_post();

        // OUTPUT MORE STUFF HERE.

    endwhile;

    wp_reset_postdata();

endif;

回答您的原始问题:它通常在endwhile之后和endif之前。 实际上是对the_post()的调用改变了全局 post 变量。 如果没有帖子,则帖子变量保持不变,没有理由使用重置功能。

暂无
暂无

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

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