I am having issues on showing posts (from “wp_posts”) in wordpress by using start date and end date (compared to “post_date”).
I want to show all posts that have a “post_date” equal to or between the chosen “start date” and chosen “end date”.

  • My query is working when I use start date = 2017-03-01 and end date =
    2017-03-31.

  • But when I query by using start date = 2017-02-28 and end date =
    2017-04-01 it shows nothing.

  • And when I query by using start date = 2017-02-28 and end date =
    2017-03-31 it only shows the posts of 2017-02-28, 2017-03-29, 2017-03-30, 2017-03-31.

It looks like that my query is just comparing basicly by day and after that by month..

Any help would be appreciated.

My code is below;

My input:

$from_date = mysqli_real_escape_string ($link, $_POST['from_date']);
$post_from_date = $from_date;
$from_date= explode("-", $from_date);
$from_day = $from_date[2];
$from_month = $from_date[1];
$from_year = $from_date[0];

$end_date = mysqli_real_escape_string ($link, $_POST['end_date']);
$post_end_date = $end_date ;
$end_date = explode("-", $end_date);
$end_day = $end_date [2];
$end_month = $end_date [1];
$end_year = $end_date [0];

My form:

<form method="POST" action="" name="events_per_period">
<label>From</label><input type="date" name="from_date" onchange="this.form.submit()" value="<?=$post_from_date;?>"/>
<label>till</label><input type="date" name="end_date" onchange="this.form.submit()" value="<?=$post_end_date;?>"/></form>

My query:

$args = array(
    'post_type'     => 'events',
    'post_status'   => 'publish',
    'posts_per_page'    => -1,
    'date_query'    => array(
        'relation'  =>   'AND',
        'column'  => 'post_date',
        'before'   => array(
            'year'  => $end_year,
            'month' => $end_month,
            'day'   => $end_day,
            ),
        'inclusive' => true,
        'after' => array(
            'year'  => $from_year,
            'month' => $from_month,
            'day'   => $from_day,
            ),
        'inclusive' => true
     ),
    'orderby' => array( 'post_date' => 'ASC' ),
);
$query = new WP_Query( $args );

Read more here: WordPress query posts on and between start date and end date [SOLVED]


Solution:

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


Wordpress related questions and answers: