How to add custom fields to search excerpts

Getting Relevanssi to index custom fields and find posts by custom field content is easy – just list the custom fields in the appropriate setting and re-index. However, Relevanssi doesn’t include custom field content in the custom search excerpts by default – it doesn’t really know how to do that.

It’s not particularly complicated, though. You can use the relevanssi_excerpt_content to add any content you want to the source material Relevanssi uses to build the excerpts. Adding custom fields is as easy as this:

add_filter('relevanssi_excerpt_content', 'custom_fields_to_excerpts', 10, 3);
function custom_fields_to_excerpts($content, $post, $query) {
    $custom_field = get_post_meta($post->ID, 'custom_field_1', true);
    $content .= " " . $custom_field;
    $custom_field = get_post_meta($post->ID, 'custom_field_2', true);
    $content .= " " . $custom_field;
    return $content;
}

This would make the contents of the custom fields “custom_field_1” and “custom_field_2” available for Relevanssi excerpt-building. Just add the code to functions.php. There’s no need to rebuild the index after adding this code, you should see the effects immediately.

  • NickToye

    Hi, does this work with Advanced Custom Fields repeater fields?

    • Yes, you just need to adjust the code so that it reads the repeater fields.

      • Peter Barr

        Hi, is there a way for this to work with all ACF fields? I have so many in a large site that listing them one by one would be massive.

      • Julian Coates

        Hi, do you have any examples of how you adjust the code to read repeater and flexible content fields? Your example is working well for standard fields but I am getting nothing at all for those.

  • Hey,
    I have add a custom field of dimension in my product post and want to get search a product by its dimension by its not working can u please help me …im using the relevanssi plugin..

    • What have you done so far?

      • I have use a plugin and its searching a product by its name and contetn..but whenever im going to give the length ,height,width..its not showing any prodcuts on search page like if i type in search box i want a prodcut of dimension like : 40WX10HX10L..the product is there in my site but its not showing me on search page..

        • add_filter(‘relevanssi_excerpt_content’, ‘excerpt_function’, 10, 3); function excerpt_function($content, $post, $query) {

          global $wpdb; $fields = $wpdb->get_col(“SELECT DISTINCT(meta_key) FROM $wpdb->postmeta”);

          foreach($fields as $key => $field){ $field_value = get_post_meta($post->ID, $field, TRUE); $content .= ‘ ‘ . ( is_array($field_value) ? implode(‘ ‘, $field_value) : $field_value ); }

          $content = preg_replace($wordlist, ”, $content);

          return $content; }

          i have add dis code in my fucntion.php file but its not giving me any output

          • Have you made Relevanssi actually index those custom fields? If not, see the custom fields option on Relevanssi settings page.

          • yes i did and increase the weight of it..but still not its not showing anything..no result found showing on search page

          • Have you rebuilt the index? Are you sure your results coming from Relevanssi in the first place?

  • Julian Coates

    I have a new site that uses ACF with repeater and flexible content fields and also Relevannsi. The search result excerpts are not good. By default there is no result snippet from the ACF fields. I have tried several methods I’ve found online to improve on this but none are fully successful. As a front end person I am sadly way out of my depth trying to work out a solution for this. ACF is pretty much ubiquitous these days so it is very important to me that I can get good search results and snippets from ACF fields. If anyone has found a good solution I would be v grateful to see it. Thanks!

    • It gets complicated, and the solutions are going to be unique to your needs. Any ACF-capable developer should be able to help you with this, the Relevanssi side of things is really simple and described in the post above.

      • Julian Coates

        Thanks for the ultra quick reply! Would you be able to provide just one hypothetical example, that maybe I could use to start figuring out what I need? For example, I have a flexible content field called “create_panels”, and in it there is a layout called “single-column”, and in that a wysiwyg field called “panel_content” that I would like to be able to show in snippets. If you could tell me how to do that, I could probably use it to sort out all the others. I find that people like me, designers turned front end developers, can generally get on pretty well if they have a few concrete examples to look at. Thanks again.

        • I’m not an ACF developer, so I don’t know. There’s a concrete example of the Relevanssi side above: you need a function on relevanssi_excerpt_content hook that reads the ACF fields and returns their content, and then it’ll be used in the excerpt-building.

          How do you do that reading of ACF fields is easy for any ACF-capable developer, but I don’t know how that happens as I don’t use ACF.

          • Julian Coates

            That makes two of us! I have already posted on ACF as well, so I’ll see if they have any suggestions. Thanks.

          • Julian Coates

            I got this from ACF support:

            ID);
            if($fields){
            foreach($fields as $field){
            $content .= ” ” . $field[‘repeater_sub_field_1’];
            $content .= ” ” . $field[‘repeater_sub_field_2’];
            }
            }
            $fields = get_field(‘flexible_field_name’, $post->ID);
            if($fields){
            foreach($fields as $field){
            if($field[‘acf_fc_layout’] == “first_layout_name”){
            $content .= ” ” . $field[‘flex_sub_field_1’];
            $content .= ” ” . $field[‘flex_sub_field_2’];
            } elseif ($field[‘acf_fc_layout’] == “second_layout_name”){
            $content .= ” ” . $field[‘flex_sub_field_4’];
            $content .= ” ” . $field[‘flex_sub_field_5’];
            }
            }
            }
            return $content;
            }
            ?>

            “You can try to print_r() your flexible and repeater custom field to see the structure of the returned field ( something like print_r(get_field(‘repeater_field_name’, $post->ID)) ). ”

            So far it is working very well.

          • Kamil

            For me also working THANKS!

          • Doug Keeling

            Thank you SO much for this! Saved me hours of searching and fussing around.

  • Jim

    Hello. I am new at this, so thank you in advance for your patience.

    I have a video website that stores video tags (Field1) in one custom table (Table1) which has it’s own ID (vID1), and video descriptions (Field2) in another table (Table2) which has it’s own ID (vID2). These videos are kept in tables that are not associated with the typical WP posts and pages. At this time, neither WP nor my theme is capable of making my current search functionality include my videos tags or descriptions. I hope that Relevanssi will be my solution!

    I have tried this:

    add_filter(‘relevanssi_excerpt_content’, ‘custom_fields_to_excerpts’, 10, 3);
    function custom_fields_to_excerpts($content, $post, $query) {
    $custom_field = get_post_meta($post->ID, ‘field1’, true);
    $content .= ” ” . $custom_field;
    $custom_field = get_post_meta($post->ID, ‘field2’, true);
    $content .= ” ” . $custom_field;
    return $content;
    }

    … and I have also tried replacing the ->ID’s with the vID1 and vID2. I am not having any luck. Also, I don’t know if there are other function.php files out there, but I inserted this into the functions.php file I found in the root of my theme folder (Did I mention I was new at this?)

    Is it possible for me to include the fields in the tables I am after? Or might other work need to be done to make Relevanssi aware of my other tables/fields? Thanks!

    • Are the videos themselves posts? If not, Relevanssi can’t help you.

      • Jim

        Wow! Thanks for the quick response Mikko. I’m not certain how tell that. I believe they are. I can see the videos in the wp_posts table, but the tags and descriptions are housed in other tables. I am able to find words that are in the titles in my search (which are in wp_posts), but not tags or words descriptions. I am hoping I am just doing the add_filter incorrectly.

        Jim

        • Yes, looks like they are a custom post type. In that case it’s very much possible.

          This filter is not helping the search, though. You need ‘relevanssi_content_to_index’ to add content to posts as they are indexed.

          Also, you can’t use get_post_meta() when the tags or descriptions are not stored in post meta. Instead you need to use database queries to fetch the data from the separate database table.

          How this is done exactly goes beyond what I can do for you here, but if you buy a Relevanssi Premium license, this is something I can do for you without extra payment.

          • Jim

            That sounds great, Mikko. However, I am concerned about performance. I do not have a lot of posts/pages (under 500) and the delay is extensive (well over a minute). Here is what I have.

            State of the Index

            Documents in the index: 498
            Terms in the index: 3826
            Highest post ID indexed: 2554

            It may be because of my settings. I had set ‘custom fields to index’ to ‘all’ and I was getting my custom tags, again, after very long delays. I attempted to delete-and-rebuild my index but my State of the Index remained the same. Maybe the ‘all’ is still in operation? I wish the ‘visible’ and ‘all’ were check box items so I could be certain they were enabled/disabled.

            I am confident that your scripting will make the search much faster, but I wasn’t seeing a good response rate even before I entered ‘all’. Is there a way I can send you my settings to see if I messed thing up on my end?

            Jim

          • Relevanssi will not make search faster; the default WP search is certainly faster.

            You have a very small index, that should not be a problem. Is the delay in indexing or in searching? If it’s in the indexing, that’s not a problem at all. If it’s in the searching, then you have a problem and you may be running a quite slow server – in that case moving the search outside your server to a cloud is a good idea.

            I’ll be glad to help if you buy a support license, otherwise I’ll have to say no.

          • Jim

            I am currently on a shared server. I’ll have to find out what my dedicated RAM is. That will eventually change, but I do not know when. I don’t mind the (very) slow index as much as I do my user’s search experience.

            Can you give me an idea of a service you recommend that works well with Relevanssi? (I currently use 1and1.com.) Essentially, I am trying to figure out what my total annual cost will be.

            Even more important, based on both your experience and the size of the index I have, can you tell me how long you think a search would take in the environment/service-level you recommend?

            Thanks. Again, I’m new to all this.

            Jim

          • With that size, really anything decent should do. I’ve run a site three times as large in a regular shared webhotel environment without issues.

            Indexing may take minutes, and that’s usual, but searches shouldn’t take more than couple of seconds.

            If you want a lightning-fast search, you should look to other options. Swiftype and AddSearch provide really fast searches, for example.

      • Jim

        …and to follow up from my last message(below), if I were to go to Dashboard > Posts, my videos would not show up there. That’s why I wasn’t certain if they were actual posts. But again, they do have records in wp_posts just like my other normal posts – only without the video’s tags and descriptions.

  • Stacey

    I’ve read through the examples suggested below for ACF custom fields, but am not able to get Relevanssi to pick up the image titles and captions that are in galleries in my posts.

    My custom field name is ‘gallery’ and here are my two failed attempts at filter code:
    http://pastebin.com/vV6gyAFQ

    Are there are any glaring mistakes that I’m missing?

    Information on the ACF Gallery field:
    https://www.advancedcustomfields.com/resources/gallery/

    • The second functions has potential. Have you checked what the get_field() returns? That’s the first thing I’d see – is the function returning the data you’re expecting it to return?

      • Stacey

        Thanks. ACF support recommended that I modify my code a little bit and use the get_field_object() instead of the get_field() function. I tried to do that with this code (http://pastebin.com/v6grnCDy), but my searches still aren’t including image titles or captions. I think I was putting the cart before the horse by focusing on search excerpts earlier. First and foremost, I need the image title’s and captions that correspond to the image ID’s in a post’s gallery field to be indexed. Do I need to query the wpdb directly? I’m so confused.

        • Stacey

          Nevermind! It works now! I needed to click “continue indexing” in Relevanssi Settings and now words in the title’s and captions of a post’s gallery are included in the search.

          This is the code I added to my functions.php file that works:

          add_filter(‘relevanssi_content_to_index’, ‘add_extra_content’, 10, 2);
          function add_extra_content($content, $post) {
          $images = get_field(‘gallery’, $post->ID);
          if($images){
          foreach( $images as $image ) {
          $content .= ” ” . $image[‘title’];
          $content .= ” ” . $image[‘caption’];
          }
          return $content;
          }
          }

          • LG

            Hi,

            I am trying to get Relevanssi to register my Exif data from the photos uploaded. However, after add in the code, it does not show up on Relevanssi’s list to be indexed. I tried to click “Continue to Index” but no luck either.

            My code is here:
            http://pastebin.com/81C2Xh6J

          • That filter doesn’t do anything for indexing. In addition to ‘relevanssi_excerpt_content’, use ‘relevanssi_content_to_index’ (see Stacey’s comment above).

            Also, you probably need to pass the post ID parameter to get_post_thumbnail_id().

          • LG

            Hi Mikko,

            I changed to the below, but the result is the same:

            add_filter(‘relevanssi_content_to_index’, ‘add_extra_content’, 10, 2);

            function add_extra_content($content, $post) {
            if ( ! is_singular( ‘download’ ) || ! has_post_thumbnail( get_the_ID() )) :
            return;
            endif;
            $post_id = get_the_ID($post);
            $image_id = get_post_thumbnail_id($post_id);
            $image = wp_get_attachment_metadata( $image_id);
            $image_meta = $image[‘image_meta’];

            if ($image_meta) {
            foreach($image_meta as $image_meta) {

            $date_shoot = date(‘d-m-Y’, $image_metadata[‘created_timestamp’]);
            $content .= ” ” . $date_shoot;
            }

            return $content;

            }
            }

          • I would recommend debugging the code: see that it runs, see that it gets the correct data. That’s the way to solve this; I can’t help you from afar.

  • Hey, great plugin and thanks for this snippet, by looking in to the Relevanssi code I’ve produced this snippet for functions.php which adds all “visible” custom fields to the custom search excerpts (as long as they’re not arrays). It’s working well for me as I use the visible setting in the custom fields to index box.

    https://gist.github.com/Jason-Murray/122c9e5e79826fa85fcadef3d364fd52

    • Dude, this is legit! Just what I need. When you say “as long as they’re not arrays” I’m guessing you’re saying “as long as they’re not in repeater fields”, huh?

      • Scratch that, an example field not indexed would be an array of page ID’s from a related post field. Repeater fields are definitely included. Awesome.

  • Guest 1

    Does the relevanssi search on the product description and postmeta values?

  • Insidea s. r. o.

    Hi, thank you very much for your great plugin. I have one question. Is it possible to search also in the image captions? I have a website where one post = one photo and only text content is in image caption. Stacey in this discussion writes something simmilar, but his code doesn`t work for me. Can you please write me what can I do? Thank you very much!
    Martin

    • If you set Relevanssi to index attachments, attachments captions are automatically indexed.

      • Insidea s. r. o.

        Thank you for your quick response!