Archived topic
How to display posts sorted by custom date-field?
1 reply · Started by Sascha on November 23, 2022
Hello, this is a follow-up to your comment on another ticket.
I have created CTP “Events” with some custom-fields like “event_date”. Now I’d like to display all events on this page, but sort them by the event_date, not the published date.
I had applied the filter you linked in your previous comment, but yet I failed to apply it properly. I don’t understand, which parts of the code to replace.
Can you help me with this? Admin-Link in private note field.
Here you find the relevant areas:
Custom Fields: Dashboard > Meta Box > Custom Fields
Custom Post Type: Dashboard > Events
Thank you in advance and kind regards,
Sascha
Hi there,
try this:
add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
// apply filter if loop has class: my-class-name
if (
! empty( $attributes['className'] ) &&
strpos( $attributes['className'], 'in-date-order' ) !== false
) {
// merge meta_key my-custom-field into query
return array_merge( $query_args, array(
'meta_key' => 'event_date',
'meta_type' => 'DATETIME',
'orderby' => 'meta_value',
'order' => 'DESC',
) );
}
return $query_args;
}, 10, 2 );
If that doesn't work then check the:
a. 'meta_key' => 'event_date', is the correct custom field name.
b. 'meta_type' => 'DATETIME', is the correct type for your custom field.