Support

Account

Home Forums Backend Issues (wp-admin) ACF Page Link – search by title only

Solved

ACF Page Link – search by title only

  • The ACF Page Link field seems to return every post/page that contains the search string. That behaviour is quite problematic on WP instances with hundreds of posts/pages.

    e.g. On a travel blog, there are dozens of posts containing the word “Thailand”, but only five posts that have “Thailand” in the title. When entering “Thailand” into the ACF Page Link field, it will return dozens of matching posts/pages, making it inconvenient to find the very posts with “Thailand” in the title.

    Is there a way to limit the ACF Page Link field to search only for page/post title?

    Thanks for your help!

  • ACF uses the WP built in search which searches the titles and content of posts. In order to search only titles you need to alter the way WP does searches. See this https://www.isitwp.com/limit-search-to-post-titles-only/

    To apply this to only one field in ACF

    
    add_fitler('acf/fields/page_link/query/name=YOUR_FIELD_NAME', 'add_search_only_titles_filter
    ', 10, 3);
    function add_search_only_titles_filter($args, $field, $post_id) {
      // only adds the search filter to this field
      add_filter('posts_search', '__search_by_title_only', 500, 2);
      return $args;
    }
    // this function copied from the source I linked above
    function __search_by_title_only( $search, &$wp_query )
    {
        global $wpdb;
    
        if ( empty( $search ) )
            return $search; // skip processing - no search term in query
    
        $q = $wp_query->query_vars;    
        $n = ! empty( $q['exact'] ) ? '' : '%';
    
        $search =
        $searchand = '';
    
        foreach ( (array) $q['search_terms'] as $term ) {
            $term = esc_sql( like_escape( $term ) );
            $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
            $searchand = ' AND ';
        }
    
        if ( ! empty( $search ) ) {
            $search = " AND ({$search}) ";
            if ( ! is_user_logged_in() )
                $search .= " AND ($wpdb->posts.post_password = '') ";
        }
    
        return $search;
    }
    
  • Thanks for guiding me in the right direction! Although, the search filter you provided contains the deprecated function like_escape(). An updated code snippet can be found on https://wordpress.stackexchange.com/a/11826/1685.

  • Sorry about the old code, I just used the first one I found that looked like it might work. Glad I could help.

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

The topic ‘ACF Page Link – search by title only’ is closed to new replies.