Hi Toolset,
I'm looking for a way to echo a custom field value from a post relationship in PHP.
I have a post type Job and Company and i would like to show the company street on the Job single page, in a PHP template. Any idea how to do this?
Thanks,
Menno
Hi, you will use the Post Relationships API to determine the ID of the related Company post. Then you can use types_render_field to display the formatted custom field value, or you can use get_post_meta to display the raw value from the database.
Post Relationships API documentation here: https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api
You can find other examples in the forum by searching for toolset_get_related_post or toolset_get_related_posts.
The types_render_field API documentation is here: https://toolset.com/documentation/customizing-sites-using-php/functions/
Click the orange "+More" button beneath any field type to show examples.
WordPress's get_post_meta documentation is available here:
https://developer.wordpress.org/reference/functions/get_post_meta/
Note that you should use the 'wpcf-' prefix for custom field slugs when you're calling WordPress functions like this.
Let me know if you need more specific guidance on this.
Hi Christian,
Thanks for your response.
Can you share a small sample of code to get a custom field value from another post type?
Thanks,
Menno
Here is an example showing how to get an ID of a "writer" post in a one-to-many post relationship with the slug 'writer-book', based on a specific book post ID, then use the writer ID to get the value of some custom field in the writer post:
$book_id = 12345;
$writer = toolset_get_related_post( $book_id, 'writer-book' );
$writer_field = types_render_field( 'some-field-slug', array( 'item' => $writer ) );
// now $writer_field holds the formatted custom field value from the writer post