Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active May 28, 2018 17:46
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/51bae1a467ecd7ec4a31bec9f626d7f6 to your computer and use it in GitHub Desktop.
Save jchristopher/51bae1a467ecd7ec4a31bec9f626d7f6 to your computer and use it in GitHub Desktop.
Tell SearchWP to index Titles from chosen ACF Relationship field (instead of indexing the stored post IDs)
<?php
function my_searchwp_acf_relationship_processor( $existing_value, $the_post ) {
if ( ! is_array( $existing_value ) ) {
return $existing_value;
}
// We want to index Titles not IDs
$content_to_index = '';
// Iterate over stored ACF Relationship field and retrieve Title for each item
foreach ( $existing_value as $related_post_data ) {
if ( is_numeric( $related_post_data ) ) {
$post_title = get_the_title( absint( $related_post_data ) );
$content_to_index .= $post_title . ' ';
} else {
$related_post_data = maybe_unserialize( $related_post_data );
if ( is_array( $related_post_data ) && ! empty( $related_post_data ) ) {
foreach ( $related_post_data as $related_post_id ) {
$post_title = get_the_title( absint( $related_post_id ) );
$content_to_index .= $post_title . ' ';
}
}
}
}
// Instead of indexing the original ACF field value (likely array of IDs)
// we will instead be indexing a string of Titles for each chosen post
return $content_to_index;
}
// Adds additional processing for ACF field with the name my_acf_relationship_field
add_filter( 'searchwp_custom_field_my_acf_relationship_field', 'my_searchwp_acf_relationship_processor', 10, 2 );
@alexheinrich
Copy link

Hi Jonathan,
I am confused why the second foreach loop (l. 20-23) is needed, since there is none if post ids are saved. It doesn't seem to work for me that way, but maybe that is just my situation?
Cheers
Alex

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