This guide walks you through sorting WordPress posts by an ACF Date Picker field, showing how to store dates, query posts with meta_query and orderby parameters, and handle date formats so your archive or loop displays content in correct chronological order; follow the step-by-step code snippets and tips to integrate this into your theme or plugin confidently.
Infrastructure Context
In live WordPress environments, issues like this are rarely isolated. We typically see them as part of a broader infrastructure pattern involving updates, plugin compatibility, performance constraints, or database integrity. Teams running WordPress at scale treat these issues as ongoing operational concerns—not one-off fixes—because reliability, security, and continuity matter once a site is in production.
Key Takeaways:
- Set the query to use the date field as meta_key and order by the correct meta type-use ‘orderby’ => ‘meta_value_num’ for ACF’s Ymd format or ‘orderby’ => ‘meta_value’ with ‘meta_type’ => ‘DATE’ for YYYY-MM-DD formats.
- Configure the ACF Date Picker to return a sortable format (Ymd or YYYY-MM-DD) and use the field name (not the field_… key) as the meta_key in queries.
- Apply sorting via WP_Query or pre_get_posts for the main loop and add caching or indexing for large datasets to avoid performance issues.
ACF Date Picker Overview
Field formats and return types
You can choose several return formats in the Date Picker: the default is Ymd (e.g., 20240214), but you may set Y-m-d (2024-02-14), d/m/Y (14/02/2024), U (Unix timestamp, e.g., 1707868800), or a DateTime object on retrieval; each format changes how you sort, compare, and cast values in queries, and it directly impacts whether you treat the meta_value as a string or number in your meta queries.
| Return format | Stored value example |
|---|---|
| Ymd (default) | 20240214 |
| Y-m-d | 2024-02-14 |
| d/m/Y | 14/02/2024 |
| U (timestamp) | 1707868800 |
- When values use Ymd you can sort numerically with meta_value_num for reliable chronological order.
- If you return U you get integers, which simplifies timestamp math and range queries by numeric comparison.
- Returning formatted strings like d/m/Y forces you to normalize or convert before sorting, since lexical order won’t match chronological order.
- Perceiving that the chosen return format dictates your WP_Query meta_type, orderby, and any casting or conversion you must perform.
How ACF stores dates in the database
ACF writes the date into wp_postmeta.meta_value as plain text using the field’s return format; the default Ymd saves values like 20240214, while U writes an integer timestamp like 1707868800, and selecting “Date Object” only affects get_field output-meta_value remains the formatted string you configured.
For example, if your field key is event_date and you save 20240214, you should use ‘meta_key’ => ‘event_date’ and ‘orderby’ => ‘meta_value_num’ to sort; alternatively, choose U and sort numerically without extra normalization-this choice directly reduces query complexity and processing when you fetch or compare large sets (10k+ rows) of date meta.
Preparing WordPress and ACF
Ensure your site runs a recent WordPress installation and that ACF (free or Pro) is active; field groups appear under Custom Fields → Field Groups. Set a location rule to Post Type = Post (or your custom type) so the date field shows on the editor, and visit Settings → Permalinks to flush rewrite rules after registering any custom post types. You should also confirm users who edit posts have the custom fields capability enabled.
Creating and configuring the Date Picker field
Create a Date Picker field (label it like “Event Date” and use a machine name such as event_date). Set the Display Format to what editors see (e.g., d/m/Y) and the Return Format to a sortable value – for example, Ymd – and mark the field required if sorting depends on it. Place the field in the field group assigned to your post type so it saves to postmeta as meta_key “event_date”.
Ensuring correct return format for reliable sorting
Set ACF’s Return Format to a machine-friendly format: Ymd (e.g., 20260203) or a Unix timestamp are the two best choices for ordering. If you use Ymd, order by meta_value_num in WP_Query; if you use a timestamp, cast it to integer and use meta_value_num as well. Your choice determines whether you use string or numeric comparison in the query.
Using Ymd (20260203) avoids lexicographic pitfalls that occur with formats like Y-m-d (2026-02-03) unless you handle string sorting carefully; Ymd sorts correctly as an integer so WP_Query with ‘meta_key’ => ‘event_date’, ‘orderby’ => ‘meta_value_num’, ‘order’ => ‘ASC’ will produce deterministic results. If you prefer timestamps, ACF saves them as integers and you can still use meta_value_num, but confirm the field’s Return Format is explicitly set to “Unix timestamp” to avoid mismatched types.
How-to: Sort Posts with WP_Query
When you build a WP_Query to sort by an ACF Date Picker, pass the ACF field key as meta_key (for example ‘event_date’) and pick orderby and order accordingly; for example, ‘meta_key’ => ‘event_date’, ‘orderby’ => ‘meta_value_num’, ‘order’ => ‘ASC’ sorts chronologically when your return format is YYYYMMDD or a Unix timestamp, while ‘meta_value’ can work for string-formatted dates with consistent padding.
Sorting by meta_key/meta_value (string vs. numeric)
You should choose ‘meta_value’ when values are textual and ‘meta_value_num’ when they’re numeric to avoid lexicographic quirks where ’10’ sorts before ‘2’; if your ACF Date Picker returns ‘Ymd’ (example: 20260203) or a Unix timestamp, use meta_value_num, whereas ‘YYYY-MM-DD’ can work with meta_value but often benefits from a type-aware query.
Using meta_query and orderby for precise control
You can define a named meta_query clause with the field key and type (for example ‘date_clause’ => array(‘key’=>’event_date’,’type’=>’DATE’)) and then set ‘orderby’ => array(‘date_clause’ => ‘ASC’), which forces SQL to cast the meta_value as DATE and gives predictable chronological ordering even with hyphenated formats.
For more control, combine multiple named clauses and orders such as array(‘date_clause’=>’ASC’,’priority_clause’=>’DESC’), use ‘compare’=>’EXISTS’ to filter posts that actually have a date, and plan for scale-meta_query-heavy queries can slow sites with thousands to millions of postmeta rows, so paginate and cache results you fetch.
How-to: Sort Posts via pre_get_posts and REST API
You can sort both front-end queries and REST responses by targeting the ACF meta key (for example ‘event_date’). For theme queries use pre_get_posts to inject meta_key, orderby and order; for the API register the meta with show_in_rest and then call /wp-json/wp/v2/posts?meta_key=event_date&orderby=meta_value_num&order=asc when the field is stored as Ymd. Use meta_value for ‘Y-m-d’ strings and prefer numeric ordering when your field is saved as YYYYMMDD or epoch seconds.
Applying pre_get_posts to archives and main queries
Hook pre_get_posts, verify is_main_query() and the target conditional (is_post_type_archive(‘event’) or is_home()), then set $query->set(‘meta_key’,’event_date’); $query->set(‘orderby’,’meta_value_num’); $query->set(‘order’,’ASC’); If ACF returns ‘Y-m-d’ switch to meta_value or add a meta_query that converts the value; test with several hundred or thousand posts and add a DB index on meta_key for large datasets.
Exposing and sorting date fields in the REST API
Register the ACF meta for REST: register_post_meta(‘post’,’event_date’,[‘show_in_rest’=>true,’single’=>true,’type’=>’string’,’auth_callback’=>function(){return current_user_can(‘edit_posts’);}]); You can then request /wp-json/wp/v2/posts?meta_key=event_date&orderby=meta_value_num&order=asc for Ymd values (use meta_value for ‘Y-m-d’). If the default REST query vars reject meta_key, expose it via rest_post_collection_params or implement a custom endpoint.
You’ll get more reliable sorting by storing a numeric timestamp meta alongside the ACF field (example epoch 1640995200), registering it with ‘type’=>’number’ and show_in_rest, then querying /wp-json/wp/v2/posts?meta_key=event_date_ts&orderby=meta_value_num&order=asc; this avoids locale/format issues, scales to thousands of posts, and lets you add an index on meta_key for faster ORDER BY performance.
Tips and Best Practices
Standardize the ACF Date Picker return format to “Ymd” or “Y-m-d” so your queries are predictable, and store dates as sortable strings or generated DATE columns. When building WP_Query, prefer meta_value_num for numeric Ymd values or cast meta_value to DATE for SQL sorting. Knowing how the field is stored lets you choose the most efficient orderby and avoid off-by-one bugs.
- Set ACF return format to Ymd for easy numeric sorting
- Use meta_value_num when values are YYYYMMDD
- Prefer generated DATE columns for proper SQL DATE sorting
- Test queries with real datasets (10k+ posts) to validate performance
Performance tips: indexing, caching, and pagination
Create a generated DATE column and index it (MySQL 5.7+/MariaDB supported) to make ORDER BY use indexes; for example, add a stored column with STR_TO_DATE(meta_value, ‘%Y%m%d’) and index that column. Use object cache or transients for repeat queries and paginate with small page sizes (10-25). Knowing that offsets become slow past ~10k rows helps you choose keyset pagination instead of large OFFSETs.
- Add a generated DATE column and INDEX it to accelerate ORDER BY
- Cache expensive WP_Query results with transients or Redis
- Use keyset pagination (WHERE meta_value < last_value LIMIT 20) for deep paging
- Benchmark queries with EXPLAIN to confirm index usage
Handling timezones, empty values, and localization
Store dates in a consistent format and convert to the site’s timezone for display; if you use DateTime fields include timezone info, otherwise treat date-only fields as local to the site. For empty meta, use meta_query with ‘EXISTS’ or provide sensible fallbacks in PHP to avoid SQL surprises. Knowing how you save and display dates prevents mismatches across users and regions.
When saving, normalize user input to a canonical format (Y-m-d or Ymd) via the acf/update_value filter so queries remain consistent; for display, use wp_date() or date_i18n(get_option(‘date_format’), $timestamp) to honor site localization and DST rules. Handle empty values by excluding them with meta_query ‘EXISTS’ or by supplying a sentinel date (e.g., 9999-12-31) for sorting; for timezone-aware fields, use DateTimeImmutable with the site’s timezone (get_option(‘timezone_string’) or timezone_offset_get fallback) to avoid shifting dates when users in different zones view them.
Factors to Consider
You should verify how the ACF Date Picker stores values, how your theme and plugins construct queries, and how many date fields you actually need to sort by; mismatches cause unexpected ordering. For example, a date stored as “20250203” requires meta_value_num, while “2025-02-03” sorts correctly with type=’DATE’. Also check performance for large sites (50k+ posts) and how imports normalize formats.
- Field return format and meta_value encoding (Ymd vs Y-m-d).
- Query method: meta_value_num, type=’DATE’, or custom SQL.
- Performance on large datasets and indexed meta keys.
- Any change to field format, import process, or plugin behavior will break existing queries unless you update the query logic.
Compatibility with themes, plugins, and page builders
You need to test how templates and builders generate loops: many themes use pre_get_posts to alter WP_Query, while Elementor and Beaver Builder may run custom queries or REST calls that bypass your pre_get_posts tweaks. WPML, Polylang, and caching plugins like WP Rocket can also affect query results and cache stale ordering, so probe a few archive pages and the builder’s query settings; if a builder exposes a meta-key sort option, align it with your ACF meta_key.
Edge cases: multiple date fields, revisions, and imports
You’ll encounter three common edge cases: posts with both start and end dates, revisions or plugin-created duplicate meta entries, and imported dates in inconsistent formats (timestamps, dd/mm/yyyy, etc.). Pick a clear priority (e.g., event_start then event_end), strip non-digit characters when importing, and run a cleanup script to normalize values to Ymd (e.g., 20250203) so meta queries behave predictably across 100-100k posts.
For multiple date fields, implement a deterministic fallback: join postmeta twice (m1 for start, m2 for end) and ORDER BY COALESCE(STR_TO_DATE(m1.meta_value,’%Y%m%d’), STR_TO_DATE(m2.meta_value,’%Y%m%d’)) to get the earliest available date; when revisions or imports create duplicate meta rows, run a single-row-per-key cleanup (use GROUP BY meta_key, meta_value normalization or a WP-CLI script) so your sort keys remain unique and indexable.
To wrap up
So you can reliably sort posts by an ACF Date Picker field by using a sortable date format (set ACF to return Ymd or cast dates), then run WP_Query with ‘meta_key’ => ‘your_field’, ‘orderby’ => ‘meta_value_num’ (or ‘meta_value’ with ‘meta_type’ => ‘DATE’), specify ‘order’ => ‘ASC’/’DESC’, and add a meta_query to exclude empty values.
FAQ
Q: How does the ACF Date Picker field store dates and how does that affect sorting?
A: ACF stores date values according to the field’s “Return Format” setting. Common formats are YYYYMMDD (Ymd) and YYYY-MM-DD (Y-m-d); some projects use Unix timestamps or DATETIME for date-time fields. If the stored value is numeric (YYYYMMDD or timestamp) use orderby => ‘meta_value_num’. If it’s a date string like YYYY-MM-DD use orderby => ‘meta_value’ with meta_type => ‘DATE’. Example for Ymd (numeric):
$args = array( ‘post_type’ => ‘post’, ‘meta_key’ => ‘event_date’, ‘orderby’ => ‘meta_value_num’, ‘order’ => ‘ASC’ );
For YYYY-MM-DD (date string):
$args = array( ‘post_type’ => ‘post’, ‘meta_key’ => ‘event_date’, ‘orderby’ => ‘meta_value’, ‘meta_type’ => ‘DATE’, ‘order’ => ‘ASC’ );
Q: How do I sort posts by an ACF date picker on archive pages (using pre_get_posts)?
A: Use the pre_get_posts hook to modify the main query for the archive. Set meta_key, orderby and order there. Example (put in functions.php):
function my_sort_archive_by_acf_date( $query ) { if ( ! is_admin() && $query->is_main_query() && is_post_type_archive( ‘event’ ) ) { $query->set( ‘meta_key’, ‘event_date’ ); $query->set( ‘orderby’, ‘meta_value_num’ ); // or ‘meta_value’ + ‘meta_type’=>’DATE’ depending on format $query->set( ‘order’, ‘ASC’ ); } } add_action( ‘pre_get_posts’, ‘my_sort_archive_by_acf_date’ );
Q: How can I handle posts with missing or empty ACF date values so they don’t break sorting?
A: Options: 1) Exclude posts without a date using a meta_query with ‘compare’ => ‘EXISTS’ or ‘!=’ => ” to fetch only posts that have a date. Example:
‘meta_query’ => array( array( ‘key’ => ‘event_date’, ‘compare’ => ‘EXISTS’ ) )
2) If you want to include them but push empties to the end, fetch only dated posts for the primary listing and display undated posts in a separate section. 3) For advanced control, use posts_clauses or posts_orderby filters to implement a SQL CASE that treats empty values as very large/small values. Excluding empties is simplest and fastest for predictable ordering.
Q: What changes when sorting by an ACF Date Time field or when timezones matter?
A: Date Time fields include time and require meta_type => ‘DATETIME’ or numeric epoch sorting. If the value is stored as DATETIME (YYYY-MM-DD HH:MM:SS) use:
$args = array( ‘meta_key’ => ‘start_datetime’, ‘orderby’ => ‘meta_value’, ‘meta_type’ => ‘DATETIME’, ‘order’ => ‘ASC’ );
If you store epoch seconds use ‘meta_value_num’. Timezones are not applied by WP when sorting meta values: store values consistently in UTC or local time and convert for display. If you need timezone-aware ordering, convert datetimes to a normalized representation (UTC or epoch) before saving or use custom SQL in a posts_clauses filter.
Q: Performance and best-practice tips when sorting large sets of posts by an ACF date field?
A: Keep the date field consistent (use a single return format). Use meta_key in queries to let WP build efficient JOINs. For large sites consider: 1) Adding an index on wp_postmeta (meta_key, meta_value) at the DB level to speed meta lookups, 2) Caching query results or using transient caching for listings, 3) Limiting queried fields or using WP_Query with ‘fields’ => ‘ids’ when only IDs are needed, 4) For very large datasets move date values to a custom table designed for indexing/queries or use custom SQL with proper indexes. Also verify you query by the actual field name (meta_key = ‘event_date’) – ACF stores the field value under the field name and stores the field key under _fieldname.
Architectural Context: Before committing to ACF long-term, review Is ACF Still the Right Choice in 2026?.
Running into ACF issues in production?
We handle ACF breakage, performance issues, and update-related failures as part of our managed WordPress operations — before they impact users.
