Support

Account

Home Forums General Issues ORDER BY ACF date field, but empty fields should be considered

Helping

ORDER BY ACF date field, but empty fields should be considered

  • Hello everyone,

    I created a “date” field with ACF (called: “showed_last”) and I would like to order the posts by the showed_last field. The ordering itself is not a problem, just using a meta_query like this:

    'meta_query' 		=> array(
    	              	
    		              array(
    			              'key'			=> 'showed_last',
    			              'compare'		=> '<=',
    			              'value'			=> date('Y-m-d H:i:s'),
    			              'type'			=> 'DATETIME'
    		              )
    	              ),
    	              'order'				=> 'ASC',
    	              'orderby'			    => 'date',
    	              'meta_key'			=> 'showed_last',
    	              'meta_type'			=> 'DATE',

    The problem: Some of the posts does not have a date in the beginning and just get one later. And they should be showed first.

    So an example.

    there are 3 posts
    post 1 -> showed_last: 20220114 0:0:0
    post 2 -> showed_last: 20220117 0:0:0
    post 3 -> showed_last: (empty/NOT EXISTS)

    The order should be:
    post 3 (because never showed)
    post 1 (last showed 14th of january)
    post 2 (last showed 17th of january)

    Is there a way to acomplish this?

    Right now I get the right order but see only post 1 and post 2.

    Thanks for your help

  • Found a work around, but if there is a better solution for the query, I would be happy 🙂

    Workaround: just add a date in the past as default value

    // default value for "showed_last" field
    function default_start_date($field) {
    	$field['default_value'] = "2000-01-01 00:00:00";
    	return $field;
    }
    add_filter('acf/load_field/name=showed_last', 'default_start_date');
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.