Created
January 9, 2025 07:14
-
-
Save benpearson/4339df6d6c8bc246a934e3ccf8fea3f0 to your computer and use it in GitHub Desktop.
WordPress: Reverse ACF query example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example: Reverse ACF query | |
*/ | |
function dt_get_related_sport_icon_positive($post) | |
{ | |
$related_sport_icon_positive = null; | |
$sports_term_objects = get_the_terms($post, 'sport_category'); | |
$sports_term_id = ($sports_term_objects) | |
? $sports_term_objects[0]->term_id | |
: null; | |
if ($sports_term_id) { | |
// Find sports posts that have the same sport taxonomy term as the bulletin | |
// Note: sport term is stored in an ACF in the sport post | |
$sport_post_query_args = array( | |
'post_type' => 'sport', | |
'meta_query' => array( | |
array( | |
'key' => 'related_sport_category', // name of custom field | |
'value' => $sports_term_id, // matches exactly "123", not just 123. This prevents a match for "1234" | |
'compare' => 'LIKE' | |
) | |
) | |
); | |
$sports_posts = get_posts($sport_post_query_args); | |
if ($sports_posts) { | |
$related_sport_icon_positive = get_field('sport_icon_positive', $sports_posts[0]->ID); | |
} | |
} | |
return $related_sport_icon_positive; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment