0

I currently have a custom post type that has two major custom fields that are need for the query.

The 'score_time' field stores time of a score. Example: 12:20 The 'score_date' stores the date the game took place. Example: 01/22/2016

I need query to display post from a specified date range and they are ordered by the 'score_time' field value

Right now I don't have the date range working, but here is the code i have right now.

$args = array(
    'post_type'      => 'score_post_type',
    'posts_per_page' => 5,
    'meta_key'       => 'score_time',
    'orderby'        => 'meta_value',
    'order'          => 'ASC',
);
  • to select post by date range, you can store the date with a timestamp format and then you can make a query with ">" and "<" – mmm Mar 18 '16 at 13:10
  • i did not understand your instruction. can you please put up an example code? sorry, i am new in php – Futaba Panda Mar 18 '16 at 13:15
1

The magic parameter ist described at WP_Query under: Custom Field Parameters

You need to add a meta_query array to your $args where you define your range.

In your case the code could look like this:

$range = array(
    '2015-05-01',
    '2015-05-31',
);
$args = array(
    'post_type'      => 'score_post_type',
    'posts_per_page' => 5,
    'meta_key'       => 'score_time',
    'orderby'        => 'meta_value',
    'order'          => 'ASC',
    'meta_query' => array(
        array(
            'key'     => 'score_date',
            'value'   => $range,
            'compare' => 'BETWEEN',
            'type'    => 'date',
        )
    ),
);

NOTE: Make sure that your date and time values are valid SQL date/time values. Your provided format MM/DD/YYYY is bad for sorting and querying. Better: YYYY-MM-DD.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.