Include ACF flexible content fields in search queries

Modify the WordPress search logic to include ACF Flexible Content fields for more accurate results.


If you’re working with Advanced Custom Field’s Flexible Content field type, you might find that the search results on your WordPress site are not as accurate as they could be. By default, WordPress will just search the title and content fields of posts in order to determine relevant results. By modifying the search logic with a meta query, however, we can ensure WordPress includes the content of flexible content fields within its search for more accurate results.

First, we’re going to modify our queries to allow wildcard searches on meta keys. This is looked at in more detail in our post on performing wildcard searches in a WordPress meta query.

In the example snippets below, we have assumed that the flexible content fields on each page is called sections and therefore the meta fields of layouts within this will start with the name sections_.


/**
 * Allow wildcards in meta search
 */

function wildcard_meta_query($where) {
    return str_replace( "meta_key = 'sections_%", "meta_key LIKE 'sections_%", $where );
}

add_filter( 'posts_where' , 'wildcard_meta_query');

We can now modify our search query to look within the post meta fields that contain the contents of our flexible content sections. In order for the meta query to be used, we have to disable the s parameter that would otherwise mean WordPress would run a standard search query on titles and body content.


/**
 * Search filters
 */

function sections_search_filter($query) {

if (!is_admin() && $query->is_main_query() && is_search() ) {

    $meta_query = [
        'relation' => 'OR',
        [
           'key' => 'sections_*',
           'value' => get_search_query(), 
           'compare' => 'LIKE',
        ]
    ];

    $query->set('s', '');
    $query->set('meta_query', $meta_query);

}

return $query;

}

add_filter('pre_get_posts','sections_search_filter');


A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones