Home Forums General Issues only show published posts in Relationship / Post / Page Link picker etc


only show published posts in Relationship / Post / Page Link picker etc

  • Hi,

    I’m linking a CPT to another CPT using either Relationship / Post Object or Page Link

    but this shows *all* Posts for a specific post type.

    How would I filter that so it would only show published posts?

    also if the related post is unpublished, it should disappear from the relationship (because it wouldn’t be able to be selected, if we only allow published)


  • I had to look it up because I was under the impression that only published posts would be returned but

    post_status (string / array) – use post status. Retrieves posts by Post Status. Default value is ‘publish’, but if the user is logged in, ‘private’ is added. Public custom statuses are also included by default. And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are ‘future’, ‘draft’ and ‘pending’.

    These are retrieved using a AJAX call.

    Anyway, these augments used in a relationship field can be altered using an acf/fields/relationship/query filter The post object field has a similar hook

    As far as the link field goes, I don’t have a clue about this one. It appears to use the built in WP link popup, but after testing, this only appears to return published posts.

  • For anyone else facing the dilemma of ACF pushing links unpublished posts with the Page Link ACF type, here’s the work around I used.

    The key here is permalinks. If you’re using pretty permalinks (and you should be) published posts will use the pretty permalinks, but unpublished posts won’t.

    So, you can use PHP’s strpos(); to check the variable for specific words in the course permalink. Here’s my example:

    <?php // Get the Post ID
    $pid = get_field('course_selection', false, false); 
    // Use that to generate the permalink
    $ppl = get_the_permalink($pid);
    // If the permalink (string) doesn't contain 'post_type' show it, cuz it's using pretty permalinks, and therefore has been published
    if(!strpos($ppl, 'post_type')):	?>
    // Your code here 
    <?php endif; ?>
  • Here’s how you can do it with a filter:

    function filter_acf_relationship ($args, $field, $post_id) {
        $args['post_status'] = 'publish';
        return $args;
    add_filter('acf/fields/relationship/query', 'filter_acf_relationship', 10, 3);
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘only show published posts in Relationship / Post / Page Link picker etc’ is closed to new replies.