Hi, I’m having a hard time trying to figure out how to do a Reverse Relationship Query.
I want to query all of a custom post type that has a relationship to another.
Basically I have a post type called projects and a post type called tasks.
In tasks the relationship is set to the project.
On the project post type I want to query every task that has that project as a relationship.
I tried following this:
https://www.advancedcustomfields.com/resources/querying-relationship-fields/
But it does not seem to be working the way I want it to.
Any help is appreciated.
OK. I got this working. Here is my code for reference.
<?php
$tasks = get_posts(array(
'post_type' => 'task',
'meta_query' => array(
array(
'key' => 'task_parents', // name of custom field
'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
'compare' => 'LIKE'
)
)
));
?>
<?php if( $tasks ): ?>
<table>
<?php foreach( $tasks as $tasks ):?>
<tr>
<td>
<a href="<?php echo get_permalink( $tasks->ID ); ?>">
<?php echo get_the_title( $tasks->ID ); ?>
</a>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
Also, to get custom fields in the “ForEach” use the following
<?php echo get_field('task_due_date', $tasks->ID); ?>
function getParents($childPostId, $parentPostType, $acfKey) {
return get_posts(array(
‘post_type’ => $parentPostType,
‘meta_query’ => array(
array(
‘key’ => $acfKey,
‘value’ => ‘”‘ . $childPostId . ‘”‘,
‘compare’ => ‘LIKE’
)
)
));
}