Home Forums General Issues Ordering In An Array In A Specific Category Reply To: Ordering In An Array In A Specific Category

  • Hi neur,

    Based on what you’ve posted, I think you’re going for something like the code below. I’ve changed a number of things:

    1. The PHP date() function isn’t used in that way. It converts an integer value of seconds into a string formatted date. If you already know the date, you can pass it as a string on its own like '2018-01-01'
    2. From this, I’ve moved the year to its own variable for easy updating. The date range can then be built dynamically
    3. You have the keys needed for sorting and the keys needed for filtering jumbled with each other. I’ve updated them to be separate and added comments above each to show what they do
    4. Finally, since the dates are in the format YYYY-MM-DD, we can use the BETWEEN value for compare to pass both dates at once

    With all of that in mind, I think this should work:

    $year = '2018';
    // Build date range from year
    $date_range = array( $year . '-01-01', $year . '-12-31' );
    $posts2018_args = array(
        'post_type' => 'events',
        'posts_per_page' => -1,
        // Sort by custom meta_key
        'meta_key' => 'event_date',
        'orderby' => 'meta_value_num',
        'order' => 'ASC',
        // Filter by custom meta query
        'meta_query' => array(
            'relation' => 'AND',
                'key' => 'event_category',
                'value' => 'Indoor Track and Field',
                'compare' => '=',
                'key' => 'event_date',
                'value' => $date_range,
                'compare' => 'BETWEEN',
                'type' => 'DATE',