I am trying to set the query in php function to be based on a custom field of type "Post Reference". Only problem is that the Post Reference fields don't appear to be stored in post_meta but rather in toolset_associations table.
Is there any simple way that I can call a function and pass in a parent_id and get a list of all posts that have an association with that post id?
The example I have is:
Post Type Furniture Type has items like beds, tables etc...
Post Type Furniture Item has a custom field of type post reference which is linked to the Furniture Type post type.
When I am on a single page for Furniture Type I want to be able to query the database via a function to get a list of all Furniture Items that have a Furniture Type of the current furniture type.
I'm aware that this can be done when using Toolset Views, however I am trying to use Elementor.
Hope you can help.
Cheers,
Pete
Hi Pete,
Thank you for waiting.
I apologize for the confusion earlier and your observation is correct. Toolset Types plugin no longer stores the ID of posts connected using the post reference field as post meta and instead uses its own post-relationship structure.
To get the related posts connected through a post reference field in a custom 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
Here is an example of usage in a custom PHP function:
$parent_post = 9;
$field_slug = 'slug-of-field';
$results = toolset_get_related_posts(
// get posts related to this one
$parent_post,
// Relationship between the posts
$field_slug,
// Additional arguments
[
// This is mandatory because we're passing just a single post as the first parameter.
'query_by_role' => 'child',
// pagination
'limit' => 9999,
'offset' => 0,
'args' => '',
'role_to_return' => 'other',
'return' => 'post_id'
]
);
print_r($results);
Feel free to replace the value of $parent_post and $field_slug, to match the target post's ID and the post reference field's slug (without "wpcf-"), respectively.
I hope this helps and please let me know if you need any further assistance around this.
regards,
Waqar
I have used the code provided by Waqar and it's working well but when I have WP Debugging on I see the following two warnings:
Warning: array_merge(): Expected parameter 1 to be an array, string given in /home/admftp/public_html/dev/wp-content/plugins/types/vendor/toolset/toolset-common/inc/autoloaded/interop/commands/RelatedPosts.php on line 316
Warning: array_key_exists() expects parameter 2 to be array, null given in /home/admftp/public_html/dev/wp-content/plugins/types/vendor/toolset/toolset-common/inc/autoloaded/interop/commands/RelatedPosts.php on line 470
Can this be safely ignored or does it need to be fixed?