See:
Unexpected results are likely occurring because the provided orderby is not valid in several ways: The datatype of input, the datatype of the date, and the naming of the field.
The query you are looking for would likely be:
'orderby' => 'CAST( datum_geschreven.meta_value AS DATETIME ) DESC',
This alone may resolve the issue, as posts will be sorted by both date and time if time is available in the field.
If the field is only date, and it is desirable for content occurring on the same date to then be sorted in “natural” order of numbered titles, it would be either:
'orderby' => "CAST( datum_geschreven.meta_value AS DATE ) DESC, CAST( REGEXP_SUBSTR( title.meta_value, '^\\d+' ) AS SIGNED ) ASC, REGEXP_SUBSTR( title.meta_value, '\\D$' )",
…if by “title” you mean a meta field named “title”.
Or:
'orderby' => "CAST( datum_geschreven.meta_value AS DATE ) DESC, CAST( REGEXP_SUBSTR( t.post_title, '^\\d+') AS SIGNED ) ASC, REGEXP_SUBSTR(name, '\\D$')",
…if by “title” you mean post_title
stored in the wp_posts
table.
If that does not get expected results according to your data structure, this would work similarly:
'orderby' => 'CAST( datum_geschreven.meta_value AS DATE ) DESC, title.meta_value ASC',
or
'orderby' => 'CAST( datum_geschreven.meta_value AS DATE ) DESC, t.post_title ASC',
The difference in these approaches is complexity versus accuracy and speed, depending on the nature of your data: e.g., you indicated that the titles are prefixed by a number. Also, the first approach expects a field with DATE and TIME, while the second is only DATE.
If the numbers in the title are only 0
through 9
, the last approach will work. However, if a number goes to 10
or 11
, one will discover that when a computer is asked to sort text (a string
), it will be sorted alphabetically, not numerically.
The third linked article goes into this in detail, but the short story is that sorting numbers stored as text alphabetically will result in something like 1, 10, 11, 2, 20, 21, 3
, instead of 1, 2, 3, 10, 11, 20, 21
. This is default behavior in almost all programming and database languages: sorting numbers within text in “natural human order” almost always requires specifying to the computer that the number is an integer
(or float
, etc.), rather than text.
The queries containing REGEXP_SUBSTR
are saying, “after sorting by the date, then sort first by any number at the beginning, treating the number at the beginning as a number (integer
), not text, then, if there is still sorting to be done, sort by anything in the title that is not a number alphabetically.”