admin管理员组文章数量:1426183
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 |1 Answer
Reset to default 0get_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; ?>
本文标签: loopgetposts changes main query
版权声明:本文标题:loop - get_posts changes main query 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745410751a2657458.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
global $post
anywhere else in your template? – Jacob Peattie Commented Jun 12, 2019 at 11:06