Problem:
How to Order child posts by “Custom Date Field” while having many-to-many relationships for custom post types?
Solution:
Orderby Custom Field works fine for normal posts or custom posts (non-relational posts). But the same solution is not possible with built-in options of Views for many-to-many relational data, so the orderby Custom date field and query filtering is being done by the following code. 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' );
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
- | 12:00 – 17:00 | 12:00 – 17:00 | 12:00 – 17:00 | 12:00 – 17:00 | 12:00 – 17:00 | - |
- | 18:00 – 21:00 | 18:00 – 21:00 | 18:00 – 21:00 | 18:00 – 21:00 | 18:00 – 21:00 | - |
Supporter timezone: Asia/Karachi (GMT+05:00)
This topic contains 18 replies, has 2 voices.
Last updated by Noman 6 years, 10 months ago.
Assisted by: Noman.