Skip to content

Instantly share code, notes, and snippets.

@hissy
Last active May 26, 2021 18:39
Show Gist options
  • Save hissy/5338996 to your computer and use it in GitHub Desktop.
Save hissy/5338996 to your computer and use it in GitHub Desktop.
#WordPress #ACF Get posts which includes same value of relationship field
<?php
// get current post
global $post;
// get custom field data.
// "custom_field_key" is custom field key (ACF relationship field), return value is array of post IDs
$relations = $post->custom_field_key;
//
$meta_array = array();
foreach ((array) $relations as $relation){
$meta_array[] = array(
'key' => 'custom_field_key',
'value' => '"' . $relation . '"',
'compare' => 'LIKE'
);
}
if (count($meta_array) > 1) $meta_array['relation'] = 'OR';
$posts = get_posts(array(
'post_type' => 'post',
'meta_query' => $meta_array
));
foreach ($posts as $post) {
setup_postdata($post);
?>
<h1><?php the_title(); ?></h1>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment