To sort posts by a custom date field using the pre_get_posts hook, you need to adjust the query parameters with the $query->set() method.
Here’s an example:
function sort_posts_by_date_field( $query ) {
// Ensure this is the main query and not in the admin area
if ( ! is_admin() && $query->is_main_query() ) {
// Make sure this is the correct post type or archive
if ( $query->is_post_type_archive( 'your_post_type' ) || $query->is_tax( 'your_taxonomy' ) ) {
// Specify your custom date field meta key
$meta_key = 'your_date_field';
// Adjust the query parameters
$query->set( 'meta_key', $meta_key );
$query->set( 'orderby', 'meta_value' );
$query->set( 'meta_type', 'DATE' ); // Set the field type to DATE
$query->set( 'order', 'ASC' ); // Or DESC for descending order
}
}
}
add_action( 'pre_get_posts', 'sort_posts_by_date_field' );
Explanation:
- Query checks:
is_admin()ensures the code doesn’t run in the admin area.is_main_query()checks if this is the main query (to avoid affecting secondary queries).
- Archive type checks:
is_post_type_archive( 'your_post_type' )ensures it’s a specific post type archive.is_tax( 'your_taxonomy' )ensures it’s a taxonomy archive.
- Sorting:
meta_key— the meta key of your custom field.orderby— specifies sorting by the meta field value.meta_type— specifies the type of the meta field asDATE.order— specifies the sort order (ASCfor ascending orDESCfor descending).
Example with a real field:
If you have a custom field with the key event_date, replace 'your_date_field' with 'event_date'.
Notes:
- Make sure the date field values are stored in the
YYYY-MM-DDformat for proper sorting. - If the date format differs (e.g.,
dd-mm-yyyy), you may need to convert the values before using them in the query.