Support

Account

Home Forums General Issues Filtering posts between two dates, based on selected month, with a meta query Reply To: Filtering posts between two dates, based on selected month, with a meta query

  • You need to use a more complex meta query that checks if the selected month lies within the range of the start and end dates. Here’s an updated version of your query that should achieve this:

    $sel_month = '05';
    $sel_year = '2024'; // Adjust as needed or get this dynamically
    $sel_month_start = $sel_year . $sel_month . '01';
    $sel_month_end = date("Ymt", strtotime($sel_month_start));
    
    $meta_query = array(
        'relation' => 'AND',
        array(
            'key'     => 'start_date',
            'value'   => $sel_month_end,
            'compare' => '<=',
            'type'    => 'DATE'
        ),
        array(
            'key'     => 'end_date',
            'value'   => $sel_month_start,
            'compare' => '>=',
            'type'    => 'DATE'
        ),
    );
    
    $query = new WP_Query(array(
        'post_type' => 'your_post_type',
        'meta_query' => $meta_query
    ));

    This code constructs a date range for the selected month and uses it to make sure the post’s start date is before the end of the selected month and the post’s end date is after the start of the selected month. And plz remember to adjust 'your_post_type' to your actual post type.