Support

Account

Home Forums General Issues WP_Query – sort by custom field and publish date

Solving

WP_Query – sort by custom field and publish date

  • I have a custom date field display_date that is used when a post is published with a future date. When i query my posts I want to first sort by display_date if set but if not fallback to ‘publish_date’. I can’t work out how to do this without making two query’s and merging. Is it possible to do this with a single query?

  • You can’t work out how to do this because there is no way to do what you are attempting to do.

    WP does not have a way to sort by 2 different values depending on which one exists. You would need to make the display date required or you would need to dynamically populate that field with the post date if no value is entered. Use an acf/save_post filter get the post date and update the field

    
    update_field('date_field', get_the_date('Ymd', $post_id), $post_id);
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.