0

I seem to be getting an extra post's data when calling get_the_time('Y'); I only have 2 posts, but I seem to be getting 3 dates? I have no idea why.

Here's the code:

<?php $args = array( 'post_type' => 'post', 'category_name' => 'celebrity');
        $loop = new WP_Query($args);
        while($loop->have_posts()) : $loop->the_post(); 
        $get_year[] = get_the_time('Y'); 
        foreach($get_year as $year) {
          echo $year;
        }
        endwhile; wp_reset_postdata(); ?>

This outputs: "2013 2013 2013"

It seems to only be doing this when I do a foreach if I just echo get_the_time it works fine, outputting two "2013".

The point of this code is that I just want a list of years that have posts. My plan was to just stick each occurrence of the year into an array, use array_unique() and echo out each year. There will probably be better ways to do this, I'm open to suggestion but this was the first thing that came to mind.

So to recap, I seem to be getting 3 dates instead of 2 when I only have 2 posts.

1 Answer 1

1

You are building your array and iterating over it at each iteration of the outer Loop. Think about what happens.

First iteration of the outer loop

$get_year becomes array('2012') and you iterate over it echoing "2012".

Second iteration

$get_year becomes array('2012',2013') and you iterate over it echoing "2012" and "2013".

Do you see what happened? You have echoed the same data twice. You are echoing the partially constructed $get_year array. The more posts you have the bigger the problem will become and I would not be surprised if it crashed the browser eventually.

Pull that foreach out of the other loop so that you only iterate over it once-- after it is has been completely constructed.

$loop = new WP_Query($args);
while($loop->have_posts()) {
  $loop->the_post(); 
  $get_year[] = get_the_time('Y'); 
}
foreach($get_year as $year) {
  echo $year;
}
wp_reset_postdata();
3
  • Ahh.. Damn loops. Thanks man, you've helped me a lot on here :)
    – UzumakiDev
    Sep 8, 2013 at 22:05
  • p.s I think I'm going to stop using : for now and stick with curly braces, as I might have caught that sooner.
    – UzumakiDev
    Sep 8, 2013 at 22:07
  • 1
    Yes, don't use that "alternative" control structure syntax. It is nothing but unreadable and prone to error, and tends to encourage poorly or nonsensically formatted code to boot. I can't stand it.
    – s_ha_dum
    Sep 8, 2013 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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