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:
- The search does not return results ordered by relevance, making it hard to find what you are looking for
- The search can’t search by URL, making it difficult to find an exact post/page if there are many posts/pages being searched
- The search will return the current page. This is usually not what you would want.
- The search returns pages and posts that are drafts
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:
- Only show published posts
- Sort the results by relevance, making it much easier to find the post you are looking for
- Search by a URL. To find an exact post, you can copy and paste the URL of that post into the search box
- 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:
- Go to Screen Options at the top of the page
- Select Field Keys
More Information
For more information:
- Advanced Custom Fields
A WordPress plugin to add advanced custom fields to pages, posts, and elsewhere.
Updated about 7 yrs, 8 mths ago (March 10, 2017). Know a better answer? Let me know!
Related categories
.User submitted comments:
Comment on this article (no HTML, max 1200 characters):
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?