Posted on

Modify excerpts with relevanssi_excerpt_content

From free 2.9.1 and Premium 1.5.8, there’s a new filter that makes modifying the excerpts easier. The relevanssi_excerpt_content filter is run after the post content is run through the the_content filter and before any other cleanup is done. This is a good point to insert for example custom field content.

The filter hook passes three parameters: first is the post content used to build the excerpt from. This is what the filter wants returned back. The other parameters contain the whole $post object to save you the trouble of fetching the post details and the search query, in case that is necessary.

add_filter( 'relevanssi_excerpt_content', 'excerpt_function', 10, 3 );
function excerpt_function( $content, $post, $query ) {
    //add whatever you want to $content here
	return $content;

35 comments Modify excerpts with relevanssi_excerpt_content

    1. You don’t need this filter for that. If your search results template uses the_excerpt() to show the excerpt, enabling the custom excerpt option is enough.

  1. Hey great plugin. One problem I’ve found is that if there are 0 hits the placeholder is replaced by blank instead of 0. In the relevanssi_show_matches function it might be better to do something like this:
    isset($data[‘title_matches’][$hit]) ? $title = $data[‘title_matches’][$hit] : $title = “0”;

    That way you’d avoid the following in the excerpt:

    “Search hits: 1 in body, in title” which should be “Search hits: 1 in body, 0 in title”

  2. Thanks for this plugin!
    I’m using it combined with Advanced Excerpt plugin to avoid the removal of html tags, but once I check the Relevanssi option “Create custom search result snippets” it removes html tags, as the normal wp excerpt.
    Is it possible to have the option “Don’t remove HTML tags”? Otherwise could you help me adding some code?

  3. To do this, do I change this line in relevanssi.php?
    $content = apply_filters(‘relevanssi_excerpt_content’, $content, $post, $query);

    Put this before it? What do the 10 and 3 mean? Where do I put the names of the custom fields so they can also show in the search results?

  4. No, you do not change Relevanssi, the whole point of using a filter is to avoid having to change the plugin files, You add the code in the functions.php file in your theme. The 10 and 3 are parameters that just have to be there.

    Replace the “//add whatever you want to $content here” with code that adds the custom fields you want to the $content variable.

  5. To functions.php file I added this, which works:
    add_filter(‘relevanssi_excerpt_content’, ‘excerpt_function’, 10, 3);
    function excerpt_function($content, $post, $query) {

    $fields = array(‘meta_results’, ‘meta_inputs’, ‘meta_purpose’, ‘meta_special’, ‘meta_references’);
    $field_name = array(‘Results’, ‘Inputs’, ‘Purpose/Function’, ‘Special Characteristics’, ‘References’);

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

    I tried to add the Titles of each Custom Field also, but my code that’s commented out didn’t work. Suggestions?

  6. Implode() only takes two parameters. Make both indexed arrays, and do a for loop, so you can have:

    $field = $fields[$i];
    $name = $field_name[$i];
    $content .= ‘ ‘. ( is_array($field_value) ? $name . ‘ ‘ . implode(‘ ‘, $field_value) : $name . ‘ ‘ . $field_value );

    Something like that?

  7. Yes, here’s the code in case another noob like me needs it. This will add in the titles of the custom fields along with their content, in the search results page. The html will not display, unless you’ve done another edit to make it appear, but I included it for clarity, so you can see that the dots are what’s adding together each piece here into a string.

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

    $fields = array(‘myfield1’, ‘myfield2’, ‘myfield3’, ‘myfield4’, ‘myfield5’);
    $field_title = array(‘Title One’, ‘Title Two’, ‘Title3’, ‘Title4’, ‘Title5’);

    foreach($fields as $key => $field){
    $field_value = get_post_meta($post->ID, $field, TRUE);
    $content .= “” . $field_title[$key] . “” . ( is_array($field_value) ? implode(”, $field_value) : $field_value );

    return $content;

  8. I wish these posts had an edit button, oopsey.
    The html disappeared from inside the quotes, so this line didn’t paste right:
    $content .= ‘ ‘ . $field_title[$key] . ‘ ‘ . ( is_array($field_value) ? implode(‘ ‘, $field_value) : $field_value );

  9. @Dama,

    I probably shouldn’t have done this, but the line in the code that stripped html is in relevanssi.php: $content = strip_tags($content);
    I commented out that line, but it probably creates a vulnerability to hackers or something to do this. Since I have all articles entered only by the superadmin, hopefully that won’t hurt me, for now.

  10. Hmm, I’ve never noticed Dama’s comment before. Yeah, Relevanssi strips the HTML automatically. I guess it could allow some HTML code. It’s not much of a security problem, really. I’ll put that on my to-do list.

  11. Can anyone point me towards how to make short code content appear in the Relevanssi excerpts?
    (As general feedback i expected this to happen automatically when I ticked the Expand Shortcodes In Post Content option.)

    It looks like the relevanssi_excerpt_content hook is the place to do it, but putting:
    $content = do_shortcode($content);
    didn’t work. My setup is using a CPT to store data, then using a short code to pull parts of that into a page that is otherwise blank. Relevanssi correctly reads the short code content for indexing / presenting results, but give me a blank excerpt.


    ps – fantastic plugin btw!

  12. I’m one that doesn’t seem to have the_excerpt or the_content used in my search_results.php template. So it always displays the full posts as results.

    Where and what code do I add to enable this – I couldn’t seem to find specific instructions for this part?

  13. I am using the script snippet “Trinzia” posted here in the comments to display my custom fields from the ACF plugin on the search result page. It works like a charm … Many thanks for your help.

    But I have one question referring to this line:

    $fields = array(‘myfield1’, ‘myfield2’, ‘myfield3’, ‘myfield4’, ‘myfield5’);

    Is it possible instead of typing all custom fields by hand to grab ALL fields with just one php command? Like you can do in the Relevanssi settings: Visible and all?

    I have so many custom fields. So it would save me a lot of work 🙂

    Many thanks in advance!

    1. Hmm, there’s no easy way to grab all custom fields in all posts. get_post_custom() gets you all custom fields from one post, but not from every post. How about you try fetching the names of the fields directly from the wp_postmeta database table?

      1. Many thanks for your fast reply! Because of my narrow PHP knowledge I don’t really understand your reply. Sorry 🙂 But do you mean there is a PHP or SQL command for fetching automatically all the names of my SQL database?

        1. $array = $wpdb->get_col(“SELECT DISTINCT(meta_key) FROM $wpdb->postmeta”);

          will fetch you a list of all meta field names in your database, but that includes everything, including hidden meta fields you may not want to index.

          1. Wow .. many thanks. But excuse me for bothering you again. I don’t know where to put your line in the script from “Trinzia” (see below) so that it will work 🙁

          2. Instead of

            $fields = array(‘myfield1’, ‘myfield2’, ‘myfield3’, ‘myfield4’, ‘myfield5’);


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

          3. Hello Mikko,
            you are my hero! Thank you so much! Finally it’s working! Over one year I was looking for a solution and now I have it: Ultimately I can search my site made of advanced custom fields so beautifully! Your plugin works like a charm and thank you so much for improving the useless WP search engine! I will go premium for sure ….

          4. Hello Mikko,

            in your latest version (3.1.6) your line of code (see above) doesn’t work anymore. In version 3.1.4 everything is fine. Is there a quick solution for it? Many thanks!

            Here is my whole script again:

            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 );

            return $content;

          5. After the update to 3.1.6. the custom fields from the ACF plugin don’t show up on the search result page anymore. Before the update everything was fine and all fields showed up. Mhhh, I think I will try a fresh WordPress + SQL installation to see what will happen …

          6. Ah, that might actually be something else. Go to lib/excerpts-highlights.php and replace the two occurrances of usort() with uasort() – that might help.

          7. Thanks Mikko, thanks for helping me out! I am so glad I can use the latest version now. I read about the usort problem on the wordress support page but I thought it would just solve the problem with the highlighting. But that’s not the case. It is helping me, too 🙂

  14. Here’s is script to add all the custom post values to the content…

    add_filter(‘relevanssi_excerpt_content’, ‘excerpt_function’, 10, 3);

    function excerpt_function($content, $post, $query){
    $relevanssi_index_post_types = relevanssi_get_custom_fields();

    $meta_values = ”;
    foreach($relevanssi_index_post_types AS $custom_post_type){
    $meta_value = get_post_meta( $post->ID, $custom_post_type, true);
    $meta_values .= $meta_value.’ ‘;

    $content .= preg_replace(“/nr|rn|n|r/”, ” “, $meta_values);

    return $content;

  15. I use WordPress in Spanish. Today I installed Relevanssi, it works fine, but I get a “Continue reading →” at the end of each item. How can I change it to a Spanish text?

    1. That’s likely coming from your theme (or WordPress, but if your WordPress in Spanish, that would be in Spanish). It definitely is not from Relevanssi. Editing your theme translation might be helpful.

  16. Hi Mikko, it seems to be impossible to index porperly page contents made with Oxygen page builder.
    I applied the trick preg_replace( ‘/[.*?]/s’, ”, $content ) to remove the shortcodes generated by Oxygen.
    Some page have term occurence but no excerpt, and some have excerpt but just the first text of my header.
    Is there a way to display correctly the text where the occurence is ?

    1. Nicolas, all I know of Oxygen is that it breaks WordPress basics left and right. I don’t know how it works exactly, so I can’t tell. Where is the page content stored in Oxygen? Is it stored in post_content or in custom fields?

Leave a Reply

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.