To Order child posts by “Custom Date Field” while having many-to-many relationships for custom post types. Please note that you will need to modify this code to add your post types, custom fields and other data to make it work for your site or setup.
I have created a custom shortcode [display_related_session_posts] and added following code in theme’s functions.php file and now the order is working good:
function display_parent_post_order_by_date_field( $atts, $content = '' ) {
extract( shortcode_atts( array(
'speaker_id' => '',
), $atts ) );
$child_args = array(
'post_type' => 'speaking-slot',
'numberposts' => -1,
'order' => 'ASC',
'meta_query' => array(array('key' => '_wpcf_belongs_speaker_id', 'value' => $speaker_id))
);
$child_posts = get_posts($child_args);
$parent_ids = array();
foreach($child_posts as $child) {
$parent_ids[] = get_post_meta($child->ID, '_wpcf_belongs_session_id', true);
}
$session_args = array(
'post_type' => 'session',
'posts_per_page' => -1,
'meta_key' => 'wpcf-start-date-time',
'orderby' => 'meta_value',
'order' => 'ASC', // We can change order from here ASC/DESC
'post__in' => $parent_ids,
);
$the_query = new WP_Query( $session_args );
// The Loop
$post_contents = '';
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$post_contents .= do_shortcode($content);
endwhile;
endif;
// Reset Post Data
wp_reset_postdata();
return $post_contents;
}
add_shortcode( 'display_related_session_posts', 'display_parent_post_order_by_date_field' );