Posted on

Indexing private custom fields for admins only

I use private custom fields. I want to index them in the administration but not on the public site. How to do ?

Initially this seems impossible to do with Relevanssi, but it’s possible.

Doing this requires Relevanssi Premium. The free version doesn’t know which custom field matches the search term, it just knows some custom field does. With the free version, you can make all custom fields private or public, not some of them. With Premium, you can have more fine-tuned control with the relevanssi_match filter hook.

Here’s the code, to be added to the theme functions.php:

add_filter( 'relevanssi_match', 'rlv_private_custom_fields' );
function rlv_private_custom_fields( $match ) {
  global $wp_query;
  if ( ! $wp_query->is_admin ) {
    $customfield_detail = json_decode( $match->customfield_detail );
    if ( isset( $customfield_detail->private_custom_field ) ) {
       $match->weight = 0;
    }
    if ( isset( $customfield_detail->another_private_field ) ) {
       $match->weight = 0;
    }
  }
  return $match;
}

Now when a search is made on the front end and the custom field that has the hit matches one of the private fields, the post weight is set to zero.

For  more sophistication, the code should probably see if the search matches other parts of the post and not zero it out if there’s a match in content, but assuming your private custom fields have content that doesn’t appear elsewhere in the post, this should work fine.

Originally asked on the WP.org support forums.

Leave a Reply

Are you a Relevanssi Premium customer looking for support? Please use the Premium support form.

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.