Last active
May 12, 2021 12:38
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Jon
I think there is a little issue with this snippet: In line 19 it should say
instead of
At least, that's what I had to change in order to get it working.