Support

Account

Home Forums General Issues acf query date

Solved

acf query date

  • Hello there,

    I need a quick “mind-help”. I am about to create a CPT with a datepicker.
    Later the CPTs should be searchable (FrontEnd-Search e.g. 13.05.2016) and filterable (FrontEnd-Option-Filter e.g. field month: 05 AND field year: 2016).

    I would like to avoid (if not necessary), splitting the CPT into categories.

    Search the date is not my “mind-problem” – it starts by figuring out how the filter-query will work. Because the return of the datepicker is one field.

    So how – if even possible – can I write the quiery?

    $args = array(
    	'numberposts' => -1,
    	'post_type' => 'CTP',
            'meta_query' => array(
    		'relation' => 'AND',
    		array(
    			'key'		=> 'month',
    			'value'		=> $month
    		),
    		array(
    			'key'		=> 'year',
    			'value'		=> $year
    		)
    	)
    );

    Any ideas? Thanks

  • You can’t do the query like that. The date picker stores the date in a single field in the format YYYYMMDD. You would need to do something like this

    
    meta_query => array(
      'relation' => 'AND',
      array(
        'key' => 'date_picker_field_name',
        'value' => $first_day_of_month,
        'compare' => '>='
      ),
      array(
        'key' => 'date_picker_field_name',
        'value' => $last_day_of_month,
        'compare' => '<='
      )
    )
    

    where $first_day_of_month and $last_day_of_month are dates in the proper format.

    Alternately you could create an acf/save_post filter that takes the value stored by ACF and creates values in two additional fields, one for year and another form month and then you those additional fields when performing the query.

  • For the query I gave above you could also use between comparing them as number values

    
    meta_query => array(
      'relation' => 'AND',
      array(
        'key' => 'date_picker_field_name',
        'value' => array($first_day_of_month, $last_day_of_month),
        'type' => 'NUMERIC',
        'compare' => 'BETWEEN'
      )
    )
    
  • Hey John,

    works like a charme. Thank you very much.

    Best, Smat

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.