(Revised answer)
So after discussing via the comments, what you really need is a custom ORDER BY
clause, which in WordPress post queries (WP_Query
), you can set the clause via the posts_orderby
filter just like you can set custom GROUP BY
clause via the posts_groupby
filter.
The order that I need is June – 2019 | May – 2019 | April – 2019 |
April – 2019
If the value of the meta eventMonth
is always in this format: {month name} - {4-digit year}
such as June - 2019
— note the dash/hypen which shouldn’t be “–” or any other special characters, then the following ORDER BY
clause can sort the posts in the order specified above: (the WordPress table prefix is assumed as being wp_
and this example sorts in descending order)
ORDER BY STR_TO_DATE( REPLACE( wp_postmeta.meta_value, '-', '1,' ), '%M %e, %Y' ) DESC
And the PHP code:
-
Modify the
ORDER BY
clause:add_filter( 'posts_orderby', 'query_order_by_filter', 10, 2 ); function query_order_by_filter( $orderby, $query ) { // Modify only if and when applicable. if ( 'eventMonth_date' === $query->get( 'orderby' ) ) { global $wpdb; $order = $query->get( 'order' ); return "STR_TO_DATE( REPLACE( $wpdb->postmeta.meta_value, '-', '1,' ), '%M %e, %Y' ) $order"; } return $orderby; }
-
When making your post/
WP_Query
queries, set theorderby
parameter toeventMonth_date
:$args = array( 'meta_key' => 'eventMonth', 'orderby' => 'eventMonth_date', 'order' => 'DESC', // ... other args. ); $query = new WP_Query( $args );
PS: If you use
get_posts()
instead ofnew WP_Query()
, make sure to setsuppress_filters
tofalse
.