Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Last active December 18, 2020 12:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/ee5eb6b00f7b27908c3c4844fec46676 to your computer and use it in GitHub Desktop.
Save jchristopher/ee5eb6b00f7b27908c3c4844fec46676 to your computer and use it in GitHub Desktop.
Tell SearchWP 3.x to index the Title from a Relationship ACF field
<?php
/**
* SearchWP VERSION 3.x
* 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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment