【问题标题】:Wordpress Multiple LoopWordPress 多循环
【发布时间】:2026-01-27 19:35:02
【问题描述】:

当我们在同一页面中有多个循环时,最好的解决方案是什么?我正在使用这个主循环:

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

<?php endwhile; endif; ?>

现在我正在尝试在同一页面(在不同位置)为特定类别名称中的精选帖子添加一个新循环,这是您的最佳选择:(“内容”只是示例)

1- 使用 get_posts();

<?php global $post;
$args = array( 'category_name' => 'destaques' );
$myposts = get_posts( $args );
foreach( $myposts as $post ) :  setup_postdata($post); ?>

   "content"

<?php endforeach; ?>

2- 使用 WP_Query();

<php $my_query = new WP_Query("category_name=destaques");
while ($my_query->have_posts()) : $my_query->the_post(); ?>

   "content"

<?php endwhile; ?>

3:使用 query_posts();

<?php query_posts( 'category_name=destaques' );
if (have_posts()) : while (have_posts()) : the_post(); ?> 

   "content"

<?php endwhile; endif; ?>

您选择哪个以及为什么?

谢谢。

【问题讨论】:

    标签: themes wordpress-theming wordpress


    【解决方案1】:

    最佳选择是 get_posts();

    这是Wordpress Function Reference for query posts的推理:

    query_posts() 函数旨在 用于修改主页面 仅循环。它不打算作为 意味着在 页。如果要单独创建 在主循环之外循环,你 应该使用 get_posts() 代替。用于 query_posts() 在除 main 可能会导致您的主循环 变得不正确并且可能 展示你没有的东西 期待。

    query_posts() 函数覆盖 并替换主查询 页。为了保持理智,请勿使用 用于任何其他目的。

    query_posts() 函数创建一个 新的 WP_Query 对象并将其分配给 全局 wp_query 变量。这 get_posts() 函数创建一个新的 没有覆盖的 WP_Query 对象 全球范围内的任何东西。

    【讨论】:

    • 对。但我仍然想知道使用 get_posts 和 WP_Query 之间的区别。
    • get_posts() 创建一个新的 wp_query,而不覆盖全局变量......这可能会提供一些额外的信息:codex.wordpress.org/Function_Reference/…
    • 嗨,Kory,感谢您的提示,我发现对于分页,我只能使用 query_posts();但前提是我声明了全局变量 $wp_query。我将使用 get_posts() 进行测试,看看是否得到相同的结果,再次感谢。
    • 太棒了,没问题。想知道它是否如您所愿?
    【解决方案2】:

    我不确定其他人,但我的选择通常是与否

    <?php 
    query_posts('showposts=1&cat=-48'); // our custom query
    if ( have_posts() ) : while ( have_posts() ) : the_post();  // Start the loop
        $img = get_post_meta($post->ID, "postimage", $single = true);//any custom fields?
    ?>
        <a href="<?php the_permalink() ?>" title="Permanent Link to <?php the_title(); ?>">
          <img src="<?php echo $img; ?>" alt="<?php the_title(); ?>" />
        </a>
    <?php
    endwhile; endif;// End the Loop and Check for Posts
    wp_reset_query(); // Reset the loop
    ?>
    <div>stuff</div>
    <?php 
    query_posts('showposts=5&cat=5'); // our custom query
    if ( have_posts() ) : while ( have_posts() ) : the_post();  // Start the loop
        $img = get_post_meta($post->ID, "postimage", $single = true);//any custom fields?
    ?>
        <h2>Title</h2>
        etc..etc..
    <?php
    endwhile; endif;// End the Loop and Check for Posts
    wp_reset_query(); // Reset the loop
    ?>
    

    这证明可以满足我的需求...

    【讨论】:

    • 嗨,Marty,抱歉耽搁了,我也更喜欢这种方法,但我在分页时遇到了一些问题,你也有这个问题吗?再次感谢。
    【解决方案3】:

    我会使用数字 3。它更容易阅读和理解。

    【讨论】:

    • 这真的是评论,而不是问题的答案。请使用“添加评论”为作者留下反馈。
    • 事后我意识到这一点。