Improve Advanced Custom Fields Relationship And Post Object Fields Search

Updated about 7 yrs, 8 mths ago (March 10, 2017). Know a better answer? Let me know!

Improve Advanced Custom Fields Relationship and Post Object Fields Search

How to get the ACF Relationship and Post Object fields to sort by search results relevance, only show published posts, search by URL, and exclude the current page

I often use the Advanced Custom Fields Relationship, Post Object or Page Link fields in WordPress, however I find that the search with these fields is lacking in these ways:

Fortunately, Advanced Custom Fields has some filters we can use to modify this search behaviour.

Here is how to modify an ACF Relationship field to:

  1. Only show published posts
  2. Sort the results by relevance, making it much easier to find the post you are looking for
  3. Search by a URL. To find an exact post, you can copy and paste the URL of that post into the search box
  4. Exclude the current page from the results.

This code would normally go in your functions.php file, or possibly in a plugin.

function your_unique_function_name($args, $field, $post_id)
{
    // 1: only show published posts
    $args['post_status'] = array('publish');

    // 2: sort by relevance
    $args['orderby'] = 'relevance';
    $args['order'] = 'DESC';
    $args['posts_per_page'] = 500;

    // 3: search by URL if a URL is entered
    if(!empty($args['s']) && substr($args['s'], 0, 4) == 'http')
    {
        $post_id_to_search_for = url_to_postid($args['s']);
        if($post_id_to_search_for)
        {
            unset($args['s']);
            $args['p'] = $post_id_to_search_for;
        }
    }

    // 4: exclude current post/page
    $args['post__not_in'] = array($post_id);

    return $args;
}
add_filter('acf/fields/relationship/query/key=field_XXXXXXXXXXX', 'your_unique_function_name', 10, 3);

The field key needs to be the correct one, and there are different filters depending on whether you are using a Relationship or Post Object field. See the links below for further information.

Note that the field key is hidden by default. To show it:

  1. Go to Screen Options at the top of the page
  2. Select Field Keys

More Information

For more information:

 

Updated about 7 yrs, 8 mths ago (March 10, 2017). Know a better answer? Let me know!

Related categories [coloured].

User submitted comments:

Tom, about 6 yrs, 2 mths ago
Thursday August 30, 2018 6:39 AM

It is possible to search only for posts with a thumbnail?

Comment on this article (no HTML, max 1200 characters):