Unfortunately, neither the docs not the forum could help me. I want to find the post ID of a one to many relationship with PHP (i think i need the parent). How can i get this?
- The ID if the child is known
- The slug of the relationship is profil-nfc
Any help?
Hi,
Thank you for contacting us and I'd be happy to assist.
To get the related posts in PHP code, you can use the "toolset_get_related_posts" function:
https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/#toolset_get_related_posts
For example, suppose you have a one-to-many relationship between "Shops" and "Books" with relationship slug "shops-books" and the current "Books" post ID is available in the $post->ID. Then the code to get the related parent "Shop" would look like this:
// get children of a grandparent
$query_by_element = $post->ID; // ID of post to get relationship from
$relationship = 'shops-books'; // relationship slug
$query_by_role_name = 'child'; // $query_by_element is a parent in this relation
$limit = 1000; // defaults
$offset = 0; // defaults
$args = array(); //nothing needed
$return = 'post_id'; // We want Post ID
$role_name_to_return = 'parent'; // We want children.
$get_results = toolset_get_related_posts(
$query_by_element,
$relationship,
$query_by_role_name,
$limit,
$offset,
$args,
$return,
$role_name_to_return
);
I hope this helps and please let me know if you need any further assistance around this.
regards,
Waqar
Unfortunately, this does not work and returns an empty array all the time. Also, I guess post parent and child were misplaced in the snippet. But with the linked docs, I got it working with just one line of code:
//retrieve parent post ID from a one to many relationsship when knowing the child post-ID
$parent_id = toolset_get_related_post( $post->ID, 'profil-nfc', 'parent' );
My issue is resolved now. Thank you!