I am querying a custom post type called ‘events’ which has a meta field called ‘event_date’ which is stored in date format. It is my desire to have three or four separate queries each looking for posts within specific time periods. The first query will be all posts within the current month, then another for the following month, then the month there after, and so on. It is important that they are separate queries and not one.

I am able to query between set dates using the code below but I wish to make these dynamic and be able to add a start date variable and an end date variable based upon the current date. I was thinking of using something similar to this code I came across which does successfully give me the month name but am struggling to use this within my WordPress query.

<?php
$d = new DateTime( 'now' );
$d->modify( 'first day of this month' );
echo $d->format( 'F' ), "n";
?>

Is there anyway I can integrate dynamic start date date and end date variables which can be current month, +1, +2, +3months, etc as required? I appreciate any help you can provide.

My query code is:

<?php
$args = array( 
    'post_type' => 'event',
    'meta_key' => 'event_date',
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'showposts' => 20,
    'meta_query' => array(
    'relation' => 'AND',
        array(
            'key' => 'event_date',
            'value' => '2014-06-01', // Lowest date value
            'compare' => '>='
        ),
        array(
            'key' => 'event_date',
            'value' => '2014-06-31', // Highest date value
            'compare' => '<='
        )
    )
);
$event_posts = new WP_Query($args);
if($event_posts->have_posts()) : 
while($event_posts->have_posts()) : 
  $event_posts->the_post();
?>
POST CONTENT HERE
<?php
    endwhile;
    else: 
?>
Oops, there are no posts.
<?php
    endif;
    ?>

Read more here: Dynamic date variables for custom post type query


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , , , ,

Wordpress related questions and answers: