Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active May 12, 2021 12:38
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 jchristopher/331f262a79c40291099ed9c9c12f329b to your computer and use it in GitHub Desktop.
Save jchristopher/331f262a79c40291099ed9c9c12f329b 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
/**
* SearchWP VERSION 4
* 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 );
@cyrillbolliger
Copy link

Hi Jon

I think there is a little issue with this snippet: In line 19 it should say

foreach ( $meta_value as $acf_relationship_item )

instead of

foreach ( $meta_value[0] as $acf_relationship_item )

At least, that's what I had to change in order to get it working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment