I am having issues on showing posts in wordpress by using start date and end date.

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

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

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

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',
            array(
                    'year'  => $from_year,
                    'month' => $from_month,
                    'day'   => $from_day,
                    'compare'   =>  '>=',
            ),
            array(
                    'year'  => $end_year,
                    'month' => $end_month,
                    'day'   => $end_day,
                    'compare'   =>  '<=',
            ),
    ),
    'orderby' => array( 'post_date' => 'ASC' ),
);
$query = new WP_Query( $args );

Read more here: WordPress query posts between start date and end date


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: