Support » Fixing WordPress » get_posts() not displaying title of current post in single.php

  • <?php $postsdubbed = get_posts(array(
      'numberposts' => -1,
      'post_type' => 'post',
      'category' => $catiddubbed,
      'order' => ASC
      )); ?>
    <?php if($postsdubbed) {?>
        <?php foreach($postsdubbed as $post)
          <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php } ?>
    <?php }?>

    What this code actually does it doesn’t take the permalink/post title of the post that it’s actually working with at that point in time in the loop, instead it simply takes the permalink/post title of the post that i’m viewing this output from. It’s able to successfully figure out how many posts there are in that category or how many posts that fit the criteria, and it runs the loop that many times, so the output essentially repeats itself.

    For example, if that code was put into a custom post type post using a conditional, it doesn’t pull out the posts / their permalinks from the category specified in the get_posts() function, instead it simply takes the permalink/post title of the custom post type post that i’m on and it’ll print it out.

    So I think the the_title() and the_permalink() simply won’t work, maybe because it’s in single.php or something. Anyway, I was hoping I could get some type of replacements of these to be used in this loop.

    or if someone could shine some light upon why this doesn’t work in the single.php file as it is intended to.

Viewing 2 replies - 1 through 2 (of 2 total)
  • review

    i.e. make sure to include setup_postdata($post) into the code
    and add wp_reset_postdata() after the end of the foreach loop.

    I don’t really see a reason to use wp_reset_postdata() when I am trying to avoid getting data from the current post. I start my loops when all the current post data that I want is added.

    So it’s like

    Current custom post type post data

    List some posts with their own data


    Using the setup_postdata($post) and adding it to the foreach loop like they did in the codex hasn’t made much of a difference for me for some reason, although it logically should. I still can’t use the_title() or the_permalink() in the foreach loop since they still are taking the title and all that from the current post instead of from the posts in the loop. I can’t access any custom fields from those posts either, it just checks if that custom field exists in the post that i’m viewing currently. However, when I use get_the_title($post->id) it works fine. The problem is, all of the things that I require, like the custom fields aren’t accessible to me any longer in the loop for some reason even after the additions to the loop.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘get_posts() not displaying title of current post in single.php’ is closed to new replies.