Documentation

View the installation guide, browse the Knowledge Base, find out about SearchWP's many hooks, get support

Process ACF Fields to Index Expected Data

Sometimes after adding Advanced Custom Fields fields to your SearchWP engine configuration, expected results still don’t show up.

This is likely due to the way ACF has stored the data. For example, let’s review how Relationship fields work. After setting up the field you’re able to pick and choose any number of entries to select and save alongside your post.

ACF Relationship field

Based on the interface of ACF it makes sense to expect that all of the entry titles of the chosen entries would then become searchable, but that’s not the case!

ACF stores only the post IDs of the chosen entries and that’s what SearchWP is indexing. That’s not very useful for your site visitors however.

Thankfully SearchWP makes it extremely easy to change the way this data is indexed, and instead of storing the post IDs as they appear in the ACF data record, we can tell SearchWP to index the Title (or anything else for that matter!)

Here’s what that looks like in practice:

<?php
/**
* Tell SearchWP to index the Title from a Relationship ACF field.
*/
function my_searchwp_read_next_field( $meta_value, $meta_key, $the_post ) {
$acf_field_name = 'read_next'; // The ACF Relationship field name.
// If we're not indexing the Read Next field, return the existing meta value.
// This logic also works for sub-fields of an ACF field as well.
if ( $acf_field_name !== substr( $meta_key, strlen( $meta_key ) - strlen( $acf_field_name ) ) ) {
return $meta_value;
}
// We're going to store all of our Titles together as one string for SearchWP to index.
$titles = '';
foreach ( (array) $meta_value as $entry ) {
if ( is_numeric( $entry ) ) {
// ACF stores only the post ID but we want the Title.
$titles .= ' ' . get_the_title( absint( $entry ) );
}
}
// $titles contains all of the Titles from the ACF Relationship field.
return $titles;
}
add_filter( 'searchwp_custom_fields', 'my_searchwp_read_next_field', 99, 3 );
view raw functions.php hosted with ❤ by GitHub

That snippet can be added to your theme’s functions.php. When your index is rebuilt, SearchWP’s indexer will run the above hook when indexing the ACF field and instead of indexing the post IDs as ACF has stored the data, it will replace those IDs with the Title for each entry.

You can adjust the hook to index any data you’d like, not just the Title!

Fix keyword search on your site. No coding required!

Now you can utilize all of the content that's gone unrecognized by native WordPress keyword search instantly with SearchWP

Get SearchWP