Skip to main contentSkip to footer

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;
  $admin_search = $wp_query->is_admin;
  if ( ! $admin_search && empty( $wp_query->query_vars ) ) {
      $admin_search = true;
  }
  if ( ! $admin_search ) {
    $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.

Your account

Not logged in. Log in to see your license details.

Search

Popular Resources

Related searches feature
John Blackbourn wrote a cool related searches feature for Relevanssi Premium. It’s included from version 1.7.4. In order to use…
WooCommerce 4.4 problems
Updating WooCommerce to version 4.4 breaks Relevanssi searches. After updating WooCommerce to version 4.4, Relevanssi searches no longer find results.…

Related Posts:

Comment Section:

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed