Dear Support-Team,
I need a JSON with some Post data vom parent 'erinnerungsort' and his childs 'chronikeintrag'. I tried some googleing, but I could not work it out.
I am trying to:
function places_query_posts_callback() {
$args = array (
'post_type' => 'erinnerungsort',
'orderby' => 'post_title',
'order' => 'ASC',
);
$query = new WP_Query( $args );
$response = array();
foreach ( $query->posts as $result ) {
// $geodata_raw = get_post_meta($result->ID, 'wpcf-geodaten', true);
// $geodata_raw = substr($geodata_raw,1,(strlen($geodata_raw)-2));
// $geodata = explode(',', $geodata_raw);
$data = array();
$data['id'] = $result->ID;
// $data['lat'] = $geodata[0];
// $data['lng'] = $geodata[1];
$data['lat'] = types_render_field("geodaten", array('post_id' => $result->ID,'format' => 'FIELD_LATITUDE'));
$data['lng'] = types_render_field("geodaten", array('post_id' => $result->ID,'format' => 'FIELD_LONGITUDE'));
$data['title'] = $result->post_title;
$data['tooltip'] = get_post_meta($result->ID, 'wpcf-tooltip');
$data['content'] = $result->post_content;
$data['teaser'] = substr($result->post_content, 0, 200);
$data['type'] = array_shift(get_the_terms($result->ID, 'artdesortes'));
$data['region'] = array_shift(get_the_terms($result->ID, 'region'));
$data['thumb'] = get_the_post_thumbnail_url($result->ID);
//$data['images'] = get_post_meta($result->ID, 'wpcf-bild');
$data['chronik'] = 'chronik';
$data['link'] = get_permalink($result->ID) ;
/* Get childs 'chronikeintrag' from parent 'erinnerungsort' */
$child_posts = types_child_posts("chronikeintrag");
foreach ($child_posts as $child_post) {
$data['chroniktitel'] = $child_post->post_title;
$data['chroniktext'] = $child_post->fields['text-chronik'];
}
array_push($response, $data);
// array_push($response, $result);
}
How do I access the parent's childs?
Thanks in advance.
Theo
Dear Theo,
In the latest version of Types plugin, you can use the new API function toolset_get_related_posts(), to get the related child posts, see our document:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_posts
Query related posts by a set of conditions.
For example:
/* Get childs 'chronikeintrag' from parent 'erinnerungsort' */
$child_posts = $books = toolset_get_related_posts(
$result->ID, // get posts related to this one
array( 'erinnerungsort', 'chronikeintrag' ), // relationship between the posts
'parent', // $result->ID is parent in given relationship
20, 1, // pagination
array(), // meta query filters?
'post_object', // return type
'child' //posts from the relationship should be returned
);
foreach ($child_posts as $child_post) {
$data['chroniktitel'] = $child_post->post_title;
$data['chroniktext'] = get_post_meta($child_post->ID, 'text-chronik', true);
}
Perfect! Thanks a lot! Your example worked fine.