I've already asked this question on wordpress.stackexchange.com
but they told me this is a plain PHP question and might have nothing to do with wordpress.
I have a fairly big problem with a function i wrote …
The function lists all posts
of a custom-post-type
for "events".
function get_event_list( $latest = true, $order = 'ASC' ) {
echo '<ul class="event-items">';
$yesterday = time() - 24*60*60;
$compare = $latest ? '>' : '<';
$current_year = '';
$args = array(
'post_type' => 'wr_event',
'posts_per_page' => -1, // show all posts
'meta_key' => 'event_date',
'orderby' => 'meta_value_num',
'order' => $order,
'meta_value' => $yesterday,
'meta_compare' => $compare
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
global $post;
$this_year = get_post_meta( $post->ID, 'event_date', true );
$this_year = date('Y', $this_year);
if ( !$latest && ( $this_year != $current_year ) ) :
// new year, output the year header
// and reset current year to this new value
echo '<li class="wrapper year"><h2>' . $this_year . '</h2></li>';
$current_year = $this_year;
endif;
get_template_part( 'inc/event', 'item' ); // creates the actual li-item
endwhile;
wp_reset_postdata();
echo '</ul>';
}
As you can see I compare the "event-date" against the current year, so I can split my list in different years. The problem I have is that get_post_meta( $post->ID, 'event_date', true );
this is only available inside the while
loop.
Currently the function above outputs this …
<ul class="event-items">
<li class="year">2012</li>
<li>Event 05</li>
<li>Event 04</li>
<li>Event 03</li>
<li>Event 02</li>
<li>Event 01</li>
<li class="year">2011</li>
<li>Event 03</li>
<li>Event 02</li>
<li>Event 01</li>
<li class="year">2010</li>
<li>Event 04</li>
<li>Event 03</li>
<li>Event 02</li>
<li>Event 01</li>
</ul>
However this structure is fairly complicated to use and semantically not really correct and useful.
I'd like to wrap each year into a new <ul>
.
Any idea how to do so? The post_meta
"event_date" is only available inside the loop. How could I compare the "event_date" with the current year and wrap the queried results into a new ul
Like so …
<ul class="event-items">
<li class="year"><div>2012</div>
<ul>
<li>Event 05</li>
<li>Event 04</li>
<li>Event 03</li>
<li>Event 02</li>
<li>Event 01</li>
</ul>
</li>
…
</ul>
Maybe there are some people who know a good and logical solution to this. Maybe I need to use get_posts()
instead of new WP_Query
however I'm not that good in PHP and have no idea how I could handle this.
Please, if anybody has an idea let me know! Thank you in advance!