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; ?>
global $post
anywhere else in your template? – Jacob Peattie Commented Jun 12, 2019 at 11:06