For those who experienced the same problem, I finally found a way to do the sort. First I created an extra CMB like this :
$cmb->add_field( array(
'id' => $prefix . 'session_gooddatebegin',
'type' => 'hidden',
) );
Then I created an action using save_post
. If the CPT “session” is being updated, thanks to $update
, I assume that the user selected a date in the CMB session_datebegin
. Hence, we now are able to update the hidden date field, putting it to the correct form :
add_action( 'save_post', 'good_dates', 99, 3);
function good_dates( $post_id, $post, $update ) {
if (get_post_type($post_id)!='session') {
return;
}
//if the post is being updated
if ($update==true) {
//begin date
$datebegin = get_post_meta( $post_id, 'session_datebegin', true );
//put to the expected form with date() and strtotime()
$datebegingood = date("mdY", strtotime($datebegin));
//update the hidden variable
update_post_meta($post_id, 'session_gooddatedeb', $datebegingood );
}
}
Finally, the sort can be performed in the archive page using the same args as before :
$args = array(
'post_type' => 'session',
'posts_per_page' => -1,
'meta_key' => 'session_datebegin',
'orderby' => 'session_datebegin',
'order' => 'ASC'
);