Support

Account

Home Forums General Issues Filter posts by just month and year values from Datepicker Custom field Reply To: Filter posts by just month and year values from Datepicker Custom field

  • @andremacola

    I achieved this in a meta_query by using REGEXP. I couldn’t find a way to do it with just dates and a range, because like you I wanted it to be year-agnostic.

    The date format by default is stored as YYYYMMDD. The following searches for a string like $$$$MM$$, where MM is your month. In other words, any 4 digits, followed by a specified 2-digit month, followed by any 2 digits.

    $filter_month = '09'; // show september only
    
    $args = array (
      'post_type'      => 'course',       // your custom post type
      'meta_key'       => 'course_date',  // your custom date field name
      'orderby'        => 'meta_value_num',
      'order'          => 'ASC',
      'meta_query' => array(
        array(
          'key'      => 'course_date',
          'compare'  => 'REGEXP',
          'value'    => '[0-9]{4}' . $filter_month . '[0-9]{2}',
        ),    
      )
    );
    
    $posts = get_posts($args);
    

    A little late, but hope this helps.