CHALLENGE: Sort posts using a custom date field
SOLUTION: Use meta_query parameter
The WordPress CMS functionality provides an option to create custom post types. We often want to display items in a particular order, mostly DESC (newest at the top).
Order using default post_date (published date)
$args = [
'post_type' => 'my_custom_post_type',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
];
$postslist = get_posts( $args );
But what if we want to store a date in a custom field ( Advanced Custom Fields plugin )? Having a custom field defined as a date allows us to have better control over data. We can also fill in the date value from the future, which is not really possible when using published_date from WordPress. In this example, the custom field name is: ‘custom_date’ and the example value will be: November 30, 2020, stored in the database as the following string: 20201130 . To render a list from newest to oldest :
$args = [
'post_type' => 'my_custom_post_type',
'posts_per_page' => -1,
'post_status' => 'publish',
'order'=>'DESC',
'orderby'=>'meta_value_num',
'meta_key'=>'custom_date',
];
$postslist = get_posts( $args );
WordPress meta_query is a very powerful tool, we can adjust query logic to our needs. Let’s try now: display all items with a custom date in the future.
// DB format for custom_date : 20201130
$today = date('Ymd');
$args = [
'post_type' => 'my_custom_post_type',
'posts_per_page' => -1,
'post_status' => 'publish',
'order'=>'DESC',
'orderby'=>'meta_value_num',
'meta_key'=>'custom_date',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'custom_date',
'value' => $today,
'compare' => '>'
),
array(
'key' => 'custom_date',
'compare' => 'EXISTS',
),
),
];
$postslist = get_posts( $args );
What about showing all items from the last 4 weeks, starting today? We can use this meta_query:
$today = date('Ymd');
$date_4_weeks_ago = strtotime($today.'- 4 weeks');
$date_4_weeks_ago_ymd_val = date('Ymd',$date_4_weeks_ago);
$args = [
'post_type' => 'my_custom_post_type',
'posts_per_page' => -1,
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'custom_date',
'value' => $today,
'compare' => '<='
),
array(
'key' => 'custom_date',
'value' => $date_4_weeks_ago_ymd_val,
'compare' => '>='
),
),
'order'=>'DESC',
'orderby'=>'meta_value_num',
'meta_key'=>'custom_date',
];
$postslist = get_posts( $args );
Summary
Wp-query – a built-in WordPress functionality – provides an option to sort elements using post_date. We can even use a custom field with a custom format (a date defined as string value Ymd) and order elements according to our needs. Using a custom field for a date is more flexible than WordPress publish_date and allows to have items with dates in the future.
Follow us for more useful tips and guidelines.
Comments
0 response