Skip to content

Instantly share code, notes, and snippets.

@searchwpgists
Created February 8, 2022 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searchwpgists/34df4838f0f41d8288093fba61fd985d to your computer and use it in GitHub Desktop.
Save searchwpgists/34df4838f0f41d8288093fba61fd985d to your computer and use it in GitHub Desktop.
Tell SearchWP 4 to index the Title from a Relationship ACF field instead of the post ID
<?php
/**
* Tell SearchWP to index the Title from a Relationship ACF field instead of the post ID
*/
add_filter( 'searchwp\source\post\attributes\meta', function( $meta_value, $args ) {
$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( $args['meta_key'], strlen( $args['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.
$content_to_index = '';
if ( is_array( $meta_value ) && ! empty( $meta_value ) ) {
foreach ( $meta_value[0] as $acf_relationship_item ) {
if ( is_numeric( $acf_relationship_item ) ) {
// ACF stores only the post ID but we want the Title.
$content_to_index .= ' ' . get_the_title( absint( $acf_relationship_item ) );
// If you want to index anything else, you can append it to $content_to_index.
}
}
}
// Return the string of content we want to index instead of the data stored by ACF.
return $content_to_index;
}, 20, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment