Skip to content

Instantly share code, notes, and snippets.

@taylorbryant
Last active March 30, 2018 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taylorbryant/08d00328ce8308531f380554740a0016 to your computer and use it in GitHub Desktop.
Save taylorbryant/08d00328ce8308531f380554740a0016 to your computer and use it in GitHub Desktop.
Reverse relationship field query for ACF as a function 🔥
function getParents($childPostId, $parentPostType, $acfKey) {
return get_posts(array(
'post_type' => $parentPostType,
'meta_query' => array(
array(
'key' => $acfKey,
'value' => '"' . $childPostId . '"',
'compare' => 'LIKE'
)
)
));
}
@taylorbryant
Copy link
Author

taylorbryant commented Mar 9, 2018

Example Usage

function getAssociatedCommunityLink() {
    $parents = getParents(get_the_ID(), 'plan', 'properties');

    if ($parents) {
        foreach ($parents as $parent) {
            $grandparents = getParents($parent->ID, 'community', 'floor_plans');

            if ($grandparents) {
                foreach ($grandparents as $grandparent) :
                    return get_the_permalink($grandparent->ID);
                endforeach;
            } else {
                return "/community";
            }
        }
    }
    
    return "/community";
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment