Home Forums General Issues get_field() related_posts [only publish posts]


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 ?


  • 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

    1. use the pre_get_posts example I provided above. Added note: I thing setting post_status to false will revert to ACF’s previous behavior $query->set('post_status', false);
    2. set the field to return post IDs or get the field without formatting by setting the 3rd argument of get_field() to false and then do your own query with post__in on the array of ID values and orderby “post__in”

    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 –

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.