SearchWP

This Documentation is for SearchWP Version 3

Available since: 1.6

searchwp_custom_fields

View Parameters »

Note: Use of this hook will require a manual reindex

Many times Custom Field data is exactly what we want included in the SearchWP index. There are times, however, when Custom Fields are used to create a relationship to other content (e.g. storing an array of post IDs). Use this filter to extract the actual content you want indexed.

Example: Advanced Custom Fields has a Relationship field that allows you to define what is considered related to the current post. Under the hood it simply stores the post IDs of the related items, but post IDs don’t make much sense to add as searchable content. To inject your own code during the time SearchWP is indexing this Custom Field and tell SearchWP to index the titles instead of the post IDs, add the following to your active theme’s functions.php:

<?php
// in this case we have three ACF Relationship fields set up, they have the names
// acf_rel_1, acf_rel_2, and acf_rel_3 (NOTE: these are the NAMES not the labels)
// ACF stores post IDs in one form or another, so indexing them does us no good,
// we want to index the title of the related post, so we need to extract it
function my_searchwp_custom_fields( $customFieldValue, $customFieldName, $thePost ) {
// by default we're just going to send the original value back
$contentToIndex = $customFieldValue;
// check to see if this is one of the ACF Relationship fields we want to process
if( in_array( strtolower( $customFieldName ), array( 'acf_rel_1', 'acf_rel_2', 'acf_rel_3' ) ) ) {
// we want to index the titles, not the post IDs, so we'll wipe this out and append our titles to it
$contentToIndex = '';
// related posts are stored in an array
if( is_array( $customFieldValue ) ) {
foreach( $customFieldValue as $relatedPostData ) {
if( is_numeric( $relatedPostData ) ) { // if you set the Relationship to store post IDs, it's numeric
$title = get_the_title( $relatedPostData );
$contentToIndex .= $title . ' ';
} else { // it's an array of objects
$postData = maybe_unserialize( $relatedPostData );
if( is_array( $postData ) && !empty( $postData ) ) {
foreach( $postData as $postID ) {
$title = get_the_title( absint( $postID ) );
$contentToIndex .= $title . ' ';
}
}
}
}
}
}
return $contentToIndex;
}
add_filter( 'searchwp_custom_fields', 'my_searchwp_custom_fields', 10, 3 );
view raw gistfile1.php hosted with ❤ by GitHub

You can also set up a different filter that’s called for a single Custom Field name specifically, see searchwp_custom_field for more information.

Parameters

Parameter Type Description
$customFieldValue Mixed

The original Custom Field value

$customFieldName String

The current Custom Field name

$post Object

The Post object being indexed

[wpforms id="3080"]