Problem: I have a Repeatable Field Group (RFG) that contains a custom field holding a post ID. I would like to use PHP to get all the RFGs associated with the current posts, then loop over and display the posts in this array in the same order as the corresponding RFGs are sorted in wp-admin.
Solution: Initialize an empty array, which will be used to hold a list of post IDs. Use the toolset_get_related_posts API to query for RFGs as child posts of the current post. Use orderby => rfg_order to sort the RFG results using the visual order applied in wp-admin. Loop over the results using foreach, get the value of the post ID custom field using types_render_field or get_post_meta, and push that value onto the empty array. Call the query_posts WordPress API and provide the array of post IDs in the post__in argument. Use orderby => post__in to preserve the sorted order of the post__in array. Example:
$insert_ids = []; // empty array initialization $child_posts = toolset_get_related_posts( get_the_ID(), 'mdsc-post-ads', array( 'query_by_role' => 'parent', 'return' => 'post_object', 'orderby' => 'rfg_order' ) ); foreach ($child_posts as $child_post) { $insert_ids[] = types_render_field( "mdsc-select-ads", array( "id"=> "$child_post->ID", "output" => "raw" )); // push each field value on to the array } query_posts( array ( 'post_type' => 'mdsc-ads', 'posts_per_page' => -1, 'post__in' => $insert_ids, // query the array of post IDs directly 'orderby' => 'post__in', ));
Then loop over those results using a standard loop:
while ( have_posts()) : the_post(); // ... the loop endwhile; wp_reset_query();
Relevant Documentation:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_posts
https://toolset.com/documentation/customizing-sites-using-php/functions/
https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters
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 |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 7 replies, has 2 voices.
Last updated by 4 years, 5 months ago.
Assisted by: Christian Cox.