Home › Forums › General Issues › get_field() related_posts [only publish posts]
Hello,
I get related posts with the fonction get_field(), but i also get drafts posts.
How can i just get the published posts from this fonction ?
Thanks
ACF used to only get published posts for relationship fields. It now gets any status post. There is not filter is ACf to change this. You will need to add a pre_get_posts filter.
Or contact the developers and request that they add a filter for this, but the ACF function that now gets the posts does not know what field the query is done for so I don’t see how they can add one. Might still be worth the time to ask.
// in functions.php
function my_acf_only_get_published_posts($query) {
$query->set('post_status', 'publish');
}
// in your template
add_action('pre_get_posts', 'my_acf_only_get_published_posts', 10, 1);
$posts = get_field('relationship_field')l
remove_filter('pre_get_posts', 'my_acf_only_get_published_posts', 10, 1);
HARH, this seems completely lame … someone obviously missed the whole picture, when ‘designing’ get_field();
This is something recent and I do not know when this was changed. As I said, at one time get_field() on the front of the site would only return published posts and/or any post the the current visitor was allowed to see. Now both post object and relationship fields call the function acf_get_psots() and this function forces 'post_status' => 'any'
and there are no filter hooks available in ACF to modify this.
Currently there are two choices
$query->set('post_status', false);
Beyond this the only advice I can give to to contact the developers. It appears that this function is used on both front and back end queries now and without adding them adding a filter to alter this in the format_value function for the field I don’t see any other way around this issue at this time.
Just to let you know, in case you hadn’t already seen the news – we’ve just shipped ACF 6.1 which includes a fix to return only published posts to the Post Object, Page Link and Relationship fields, as well as a new post status filter control you can use when creating the field.
Read more here –
https://www.advancedcustomfields.com/blog/acf-6-1-0-released/#post-status-filter
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.