Home Forums General Issues Reverse Relationship Query


Reverse Relationship Query

  • 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:

    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.

    $tasks = get_posts(array(
    	'post_type' => 'task',
    	'meta_query' => 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 ): ?>
    	<?php foreach( $tasks as $tasks ):?>
    				<a href="<?php echo get_permalink( $tasks->ID ); ?>">
    					<?php echo get_the_title( $tasks->ID ); ?>
    	<?php endforeach; ?>
    <?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(
    ‘key’ => $acfKey,
    ‘value’ => ‘”‘ . $childPostId . ‘”‘,
    ‘compare’ => ‘LIKE’

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Reverse Relationship Query’ is closed to new replies.