简体   繁体   中英

Filter wordpress posts by custom date range input

I have a custom post type 'lesson' and it has a custom field attached to it called 'date of lesson. The date range and query works fine, however I need to allow the user to input the date range themselves and then have the list update (eg for this month, or for this week) and can't seem to work out how to allow them to input dates and then update the query with this. For reference, the query from taxonomy-subject.php:

$args = array(

       'meta_key' => 'date_of_lesson', // The meta key to sort on
       'orderby' => 'meta_value',
       'order' => 'ASC',
       'posts_per_page' => -1,
       'meta_query' => array(
    array(
        'key' => 'date_of_lesson',
        'value' => array($startdate, $enddate),
        'compare' => 'BETWEEN',
        'type' => 'DATE'
    )
)

Many thanks for any help.

You have to just convert the date that the user is giving in strtotime format and then change it to ' yyyy-mm-dd '(2016-05-24) format and pass in this query. If this format is not passed the query will return empty result.

User Selected Input should be changed as per this format below as start date and end date.

$start = '2011-11-31';
$end = '2011-10-01';
$args = array(
    'post_type' => 'YOUR-POST-TYPE',
    'posts_per_page' => -1,
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_key' => 'date_of_lesson',
    'meta_query' => array(
        array(
            'key' => 'date_of_lesson',
            'value' => array($start, $end),
            'compare' => 'BETWEEN',
            'type' => 'DATE'
        )
    )
);
// Make the query
$events_query = new WP_query();
$events_query->query($args);

Basically you need to set up a form on the page that displays your data with your from and to dates, using something like jQuery date picker makes life easier and keeps them to one field.

When submitted, get the values and check the format of them and make sure it is YYYY-MM-DD as per https://codex.wordpress.org/Class_Reference/WP_Meta_Query . You might need to use http://php.net/manual/en/function.strtotime.php and then http://php.net/manual/en/function.date.php if you don't have your date in the right format.

When the form is posted, be sure to keep the posted date values in your form (value="" etc...), so the user can easily adjust what they are looking at and then submit the form again to make any adjustments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM