Skip to content

Instantly share code, notes, and snippets.

@hissy
Last active May 26, 2021
Embed
What would you like to do?
#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