1

I have a loop which displays all the posts of the "events" post type on my site. Each of these posts has a custom date field "event_date", which I sort the display of the loop by.

I would like to simplify my post management by only display posts which match the current month; that is, as of today (Dec.30) all the December posts display but on January 1, all the January posts display.

Note this is not post date, it's the value of the field (when the event takes place). I want to keep the month's worth of posts up ll month even when their date passes -- so always the complete month.

Most of the posts I found here with search are dealing with the post date, whereas I need to use the value of this custom field instead. Thanks. My current query:

$args = array( 'post_type' => 'hh_event', 'posts_per_page' => -1,'orderby' => 'meta_value', 'meta_key' => 'event_date', 'order' => 'ASC'  );
            $the_query = new WP_Query( $args );

To add to this, the field is a custom field made with the Advanced Custom Fields plugin, and the date is save by this as yymmdd.

1 Answer 1

0

You can use the meta_query parameter to display all events for the current month like this:

$start_date = date( 'ym01' );
$end_date = date( 'ymt' );
$meta_query = array(
    'key'       => 'event_date',
    'value'     => array( $start_date, $end_date ),
    'compare'   => 'BETWEEN',
    'type'      => 'NUMERIC'
);
$args = array(
    'post_type'         => 'hh_event',
    'posts_per_page'    => -1,
    'orderby'           => 'meta_value',
    'meta_key'          => 'event_date',
    'order'             => 'ASC',
    'meta_query'        => array( $meta_query )
);
$the_query = new WP_Query( $args );
6
  • Makes sense to me except for the ym01 amd ymt parameters. What are those? I just plugged this into my code and got no results.
    – Steve
    Commented Dec 30, 2012 at 22:00
  • y = two digit year, m = two digit month, t = number of days in the month
    – aaronwaggs
    Commented Dec 30, 2012 at 22:11
  • I tested by adding a custom field event_date and adding values like 121230 to represent today (December 30, 2012)
    – aaronwaggs
    Commented Dec 30, 2012 at 22:16
  • Of course. Actually, I changed it to Y (4 digit year) and it works. My dates were 20121231. How would I modify this to show the month after the current month instead? Thanks,
    – Steve
    Commented Dec 30, 2012 at 22:16
  • $start_date = date( 'ymd', strtotime( 'first day of next month' ) );, $end_date = date( 'ymd', strtotime( 'last day of next month' ) );
    – aaronwaggs
    Commented Dec 30, 2012 at 22:26

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.