WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 1 down vote accepted

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()) {
  $get_year[] = get_the_time('Y'); 
foreach($get_year as $year) {
  echo $year;
share|improve this answer
Ahh.. Damn loops. Thanks man, you've helped me a lot on here :) – UzumakiDev Sep 8 '13 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 '13 at 22:07
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 '13 at 22:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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