setup_postdata doesn`t seem ot be working

I’m having issues with setup_postdata(). From my understanding, if I want to use functions such as the_permalink() or the_title(), I must use setup_postdata().

Right now, the_permalink() or the_title() is returning nothing (blank). I’ve also tried echo get_the_title() to see what happens but even that yields the same result.

Read More

Here is the code the relates to the problem:

  $posts = get_posts($args);
  foreach($posts as $post) {
    setup_postdata($post);
  ?>
  <article class="col two tablet-four mobile-six box">
    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
      <div class="featured-image">
      <?php if(has_post_thumbnail(get_the_ID())): ?>
        <?php $image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), array(650,200)); ?>
        <div style="background: url('<?php echo $image[0]; ?>') center center no-repeat;"></div>
      <?php endif; ?>
      </div>
      <section class="content">
        <?php $cat = get_the_category(get_the_ID()); ?>
        <span class="category"><?php echo $cat[0]->cat_name; ?></span>
        <?php the_title(); ?>
        <?php the_excerpt(); ?>
      </section>
    </a>
  </article>
  <? }
  wp_reset_postdata();

So basically, this code is within a function that is a callback function for an AJAX request. The function grabs the next set of posts to simulate someone clicking the next page button.

After get_posts() the $posts variable gets populated by the proper posts so it is getting something.

Right now, it responds with just the tags with no data in them.

Thanks.

Related posts

1 comment

  1. According to the Codex, you seem to skip the most important global $post; at the beginning, like this:

    global $post;
    $posts = get_posts($args);
      foreach($posts as $post) {
        setup_postdata($post);
      ?>
      <article class="col two tablet-four mobile-six box">
        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
          <div class="featured-image">
          <?php if(has_post_thumbnail(get_the_ID())): ?>
            <?php $image = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), array(650,200)); ?>
            <div style="background: url('<?php echo $image[0]; ?>') center center no-repeat;"></div>
          <?php endif; ?>
          </div>
          <section class="content">
            <?php $cat = get_the_category(get_the_ID()); ?>
            <span class="category"><?php echo $cat[0]->cat_name; ?></span>
            <?php the_title(); ?>
            <?php the_excerpt(); ?>
          </section>
        </a>
      </article>
      <? }
      wp_reset_postdata();
    

Comments are closed.