0

I am using WP_Query to get all posts from a custom post type. This works great for listing out all the posts. However, the post itself has a custom date field and I want to list all posts for a certain month under an H2 tag that list the month without repeating the month. Currently I can loop through all posts but the H2 with the month gets spit out every time. I don't want to make a month category either. The posts are for show dates. I want to list out all the dates for June but only have one H2 with June in it and then all the posts under it.

Like this:

 1. June
    a. Show date
    b. Show date
    c. Show date
 2. July
    a. Show date 
    b. Show date
    c. Show date

and not this:

 1. June
    a. Show date
 1. June
    b. Show date
 1. June 
    c. Show date
 2. July
    a. Show date
 2. July
    b. Show date
 2. July
    c. Show date

Updated code:

$current_month = '';                    
while ($query->have_posts()) : $query->the_post();?>  
<?php $date = strtotime( get_field('date') ); $month = date('F',$date); ?
<div class="row"><div class="span10">
   <h2>
     <?php if ($month != $current_month){
               $current_month = $month;
            echo $month; } ?>
1
  • Have u seen this question?
    – Steve
    Commented Jun 20, 2013 at 4:02

2 Answers 2

0

Well, you still have to order the posts by your date key, but as far as output, the general idea is to store the current month in a variable and check it against the date of each post, and only output it when it changes. A pseudo-code example:

$current_month = '';
while( have_posts() ){
    the_post();
    $this_month = get_post_meta( get_the_ID(), 'your_date_key', true );
    if( $this_month != $current_month ){
        $current_month = $this_month;
        echo '<h2>' . $current_month . '</h2>';
    }
}
3
  • I tried that at first but it only echo the last month
    – pelachile
    Commented Jun 20, 2013 at 5:08
  • add the code you've tried to your question.
    – Milo
    Commented Jun 20, 2013 at 5:19
  • I figured out with Milo's help. I'll post the update code to my answer.
    – pelachile
    Commented Jun 21, 2013 at 0:36
0

You can use Time parameter in wp_query for getting the post filter on month

$today = getdate();
$query = new WP_Query( 'year=' . $today["year"] . '&monthnum=' . $today["mon"] . '&day=' . $today["mday"] );

http://codex.wordpress.org/Class_Reference/WP_Query#Time_Parameters

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.