最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

loop - get_posts changes main query

programmeradmin2浏览0评论

Here is my code in single.php :

<?php if (have_posts()):the_post() ?>
    <h3><?php the_title() ?></h3> <!-- Prints `Hello World` -->
    <?php if (!empty($someOtherPosts = get_posts(['posts_per_page' => 3]))): ?>
        <ul>
            <?php foreach ($someOtherPosts as $post): ?>
                <li><?php echo $post->post_title ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
    <h3><?php the_title() ?></h3> <!-- Prints `Bye World` -->
<?php endif; ?>

Why am I getting different title in the next the_title() call and how can I manage this?

Here is my code in single.php :

<?php if (have_posts()):the_post() ?>
    <h3><?php the_title() ?></h3> <!-- Prints `Hello World` -->
    <?php if (!empty($someOtherPosts = get_posts(['posts_per_page' => 3]))): ?>
        <ul>
            <?php foreach ($someOtherPosts as $post): ?>
                <li><?php echo $post->post_title ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
    <h3><?php the_title() ?></h3> <!-- Prints `Bye World` -->
<?php endif; ?>

Why am I getting different title in the next the_title() call and how can I manage this?

Share Improve this question asked Jun 12, 2019 at 10:54 sarahsarah 31 bronze badge 2
  • Have you written global $post anywhere else in your template? – Jacob Peattie Commented Jun 12, 2019 at 11:06
  • no I haven't. If you put the piece of code in single.php you probably get the same result – sarah Commented Jun 12, 2019 at 11:08
Add a comment  | 

1 Answer 1

Reset to default 0

get_posts() isn't modifying the main query. The problem is that you're overwriting the global $post variable in your foreach loop. I guess if you're in a template then you're in the same scope as the global variable and don't need to specify global $post; for this to happen (as you would if you were inside a function). Rename $post in your loop and the issue will go away:

<?php if (have_posts()):the_post() ?>
    <h3><?php the_title() ?></h3>
    <?php if (!empty($someOtherPosts = get_posts(['posts_per_page' => 4]))): ?>
        <ul>
            <?php foreach ($someOtherPosts as $someOtherPost): ?>
                <li><?php echo $someOtherPost->post_title ?></li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
    <h3><?php the_title() ?></h3>
<?php endif; ?>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论