1

I am trying to organize posts by year, based on what's been entered in the Advanced Custom Fields date picker (not the year published). I've been able to come very close to what I'm looking for using the year checker found on: http://alex.leonard.ie/2009/08/27/wordpress-grouping-posts-by-monthyear/

What I'm trying to accomplish is:

2015

  • Past Exhibition
  • Past Exhibition
  • Etc.

2014

  • Past Exhibition
  • Past Exhibition
  • Etc.

2013

  • Past Exhibition
  • Past Exhibition
  • Etc.

The only problem is, while I am successfully able to print the year, only one exhibition under each year is listed.

    <?php if (have_posts()) : ?>
    <?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $today = date('Ymd');

    $past_args = array(
        'paged' => $paged,
        'posts_per_page' => -1,
        'post_type' => 'exhibitions',
        'meta_query' => array (
            array (
                'key' => 'end_date',
                'value' => $today,
                'compare' => '<',
                'type' => 'DATE'
            )
        ),
        'orderby' => 'meta_value_num',
        'order' => 'DESC'                   
    );
    query_posts( $past_args );
    ?> 


    <!-- PAST EXHIBITIONS -->
    <?php while (have_posts()) : the_post(); ?>

    <?php   
        $date = get_field('end_date');
        $past_year = DateTime::createFromFormat('Ymd', $date);
        $year = $past_year->format('Y');

        if ($year !== $today) { ?>
            <article class="year-<?php echo $year; ?> child-page four columns">
            <h2><?php echo $year; ?></h2>
            <ul>
                <li>
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                    </a>
                </li>
            </ul>
            </article>
        <?php }

        $today = $year; ?>

    <?php endwhile; ?>
    <?php endif; ?>

What am I missing/doing wrong?

alyssaster
  • 13
  • 5

1 Answers1

0

The answer is quite simple actually. Take the post content etc out of the if statement.

You want to only print the year once, but show all posts.

<?php while (have_posts()) : the_post(); ?>

<?php   
    $date = get_field('end_date');
    $past_year = DateTime::createFromFormat('Ymd', $date);
    $year = $past_year->format('Y');

    if ($year !== $today) { ?>
        <h2><?php echo $year; ?></h2>
    <?php } ?>
    <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php $today = $year; ?>

<?php endwhile; ?>

You'll have to do some playing around to get your ul and article elements opening and closing where you want, but by using the if statement only for echoing the year, the rest of your loop should proceed as normal.

alexleonard
  • 1,314
  • 3
  • 21
  • 37
  • Thank you! This really was so simple! I think I had just needed to step away from it a little while and have fresh pair of eyes look at it. – alyssaster Feb 12 '15 at 16:19