Just in case it’s playing a part, you reference the wrong callback in the code above. Your function is named “dc_sort_dates” and your add_action line references “dc_sort_date” without an S at the end.
Otherwise, this is just a setup of some posts of a date_hub post type and viewing the term archive for a taxonomy assigned to that post type? It should show up to 6 posts, newest (2018) first, and move back through time in sequential order?
Can you also verify what sort of values are being saved to your metadata? I’m curious if it’s not able to properly infer it as a date.
Thread Starter
Layson
(@glennlaysonjr)
Correct it was a typo on my part when I posted to the forum. I checked my script and it is matching.
It is being saved using the text_date field that saves the data as 01/07/2018. I have checked this by displaying the selected date in the post and it shows all data.
I also tested and added a date form 2016 and it show up before the 2017 posts. Not sure what all is happening.
So as of right now its displaying the post by year going from oldest to newest but then in the months its being displayed within that year the newest month/day to the oldest.
Any thoughts? @tw2113
I’ll need to set up my own instance for these details to try and confirm anything.
As an alternative idea, it may be worth considering storing the data as UTC timestamps, which would very easily be sorted properly. There are field types available for that. However any existing posts would need to have the date re-saved to update the post meta.
Nonetheless, added it to my todo for some debugging.
So, I’ve done some tire kicking, and this is what I’ve come to a conclusion about.
The issue at hand is not anything to do with CMB2 specifically. It’s an issue with dates having a tendency to suck, when it comes to dealing with programmatically.
First up, I would recommend storing the actual meta value in a “Y/m/d” or very similar format. It does very much help with the process of ordering. The pre_get_posts filter you have looks solid and is matching what I have working locally.
Regarding a possible different format for actual display for the date value, it’s easy enough to pass the meta value through the date() function + strtotime() to get a different version.
$mydate = get_post_meta( get_the_ID(), 'dc_datehub_dc_date', true );
echo date( 'M, d, Y', strtotime( $mydate ) );
I’d consider it a worthwhile compromise if it means dates ordered correctly.
Example CMB2 field for this, based on yours above.:
$cmb->add_field( array(
'name' => __( 'Event Date', 'date_hub' ),
'id' => $prefix . 'dc_date',
'desc' => 'Date - NOTE: Must Have to Display!',
'type' => 'text_date',
'date_format' => 'Y/m/d',
) );
Thread Starter
Layson
(@glennlaysonjr)
Worked great! Now I just have to have a script run in the plugin update to change the current metadata.
Thanks!