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?

  • Have you written global $post anywhere else in your template? – Jacob Peattie Jun 12 at 11:06
  • no I haven't. If you put the piece of code in single.php you probably get the same result – sarah Jun 12 at 11:08
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; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.