Background Info:
get_field() has three parameters:
$field_name
: the name of the field to be retrieved. eg "page_content" (required)
$post_id
: Specific post ID where your value was entered. Defaults to current post ID (not required). This can also be options / taxonomies / users / etc
$format_value
If you were only concerned with grabbing a specific post (of which you knew the ID), the key would be the second parameter ($post_id
). There's nothing really magical about ACF. Quite simply: the meta_value
(i.e. the directory listing the post is tied to) is saved to each post (attached to that post's $post_id
).
However, in your case, we don't know the ID of the post(s) we want to get.
Solution:
If we explain what you want to do in a simple sentence, that sentence would look something like:
Show/get posts on a directory_listings
(custom post type) page which have a meta_value
which points to that page.
Obviously, you can't use get_field()
, because your problem has nothing to do with "getting a field." Rather, you need to "find the posts that have a specific field." ACF has great documentation on this.
Luckily for you, WordPress ships with an awesome class called a WP_Query, and a similarly awesome function called get_posts(). So looking back at our sentence above and translating it into a function, we want to: get_posts()
where the meta_key
has a value
of the current $post_id
.
Or, more specifically, on your directory_listings
page, you'd have the following query:
$related_articles = get_posts(array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'related_articles', // name of custom field
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
)
)
));
if( $related_articles ):
foreach( $related_articles as $article ):
// Do something to display the articles. Each article is a WP_Post object.
// Example:
echo $article->post_title; // The post title
echo $article->post_excerpt; // The excerpt
echo get_the_post_thumbnail( $article->ID ); // The thumbnail
endforeach;
endif;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…