10

how can I include a line-break inside the_excerpt. I’ve modified the length and the more-button via my functions.php. I’m using teaser for every blog-entry and sometimes it looks a bit ugly, that there no line-breaks included.

6 Answers 6

6

Same to Johannes Pille's solution, the bellowing solution should be more adaptive.

In detail:

  • override function wp_trim_excerpt
  • remove old filter and add new custom new filter

Here's full code:

// append to themes/{your_theme}/functions.php

define('EXCERPT_RARELY', '{[}]');
define('EXCERPT_BR', nl2br(PHP_EOL));

function so306588_trim_excerpt_custom($text = '')
{
    add_filter('the_content', 'so306588_trim_excerpt_custom_mark', 6);

    // get through origin filter
    $text = wp_trim_excerpt($text);

    remove_filter('the_content', 'so306588_trim_excerpt_custom_mark', 6);

    return so306588_trim_excerpt_custom_restore($text);
}

function so306588_trim_excerpt_custom_mark($text)
{
    $text = nl2br($text);
    return str_replace(EXCERPT_BR, EXCERPT_RARELY, $text);
}

function so306588_trim_excerpt_custom_restore($text)
{
    return str_replace(EXCERPT_RARELY, EXCERPT_BR, $text);
}

// remove default filter
remove_filter('get_the_excerpt', 'wp_trim_excerpt');

// add custom filter
add_filter('get_the_excerpt', 'so306588_trim_excerpt_custom');
2
  • 1
    I like. +1. Had the OP accepted mine ever, I'd comment "This should be the accepted answer (now)." Commented Jul 2, 2018 at 17:50
  • Worked perfectly, until it stopped working a few days ago... But I have not been able to narrow the error down yet. But since @Nitzki commented similiary on Johannes' solution, I guess wordpress did something in a recent update that killed it... Commented Oct 29, 2020 at 16:10
4

There is no filter that would allow you to set allowable tags not to be removed by the_excerpt(). Arguably a shortcoming of the core.

Anyhow, the actual excerpt generation does not happen in that template tag but entirely elsewhere:

Excerpts are generated by the function wp_trim_excerpt(), inside of which the excerpt filters you are already using (excerpt_length and excerpt_more) are applied and which calls wp_trim_words(), which in turn calls upon wp_strip_all_tags(). All three functions are located in wp-includes/formatting.php

Hence in the absence of a filter for the case and the inevitability of your excerpt running through wp_strip_all_tags(), the only possibility to preserve some tags is adding a custom replacement function for wp_trim_excerpt():

function wpse67498_wp_trim_excerpt( $text = '' ) {
    $raw_excerpt = $text;

    if ( '' == $text ) {
        $text = get_the_content( '' );
        $text = strip_shortcodes( $text );
        $text = apply_filters( 'the_content', $text );
        $text = str_replace( ']]>', ']]>', $text );
        $excerpt_length = apply_filters( 'excerpt_length', 55 );
        $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[...]' );

        $allowable = '<br>';
        $text = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $text );
        $text = trim( strip_tags( $text, $allowable ) );

        if ( 'characters' == _x( 'words', 'word count: words or characters?' )
            && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) )
        {
            $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
            preg_match_all( '/./u', $text, $words_array );
            $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
            $sep = '';
        } else {
            $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
            $sep = ' ';
        }

        if ( count( $words_array ) > $excerpt_length ) {
            array_pop( $words_array );
            $text = implode( $sep, $words_array );
            $text = $text . $excerpt_more;
        } else {
            $text = implode( $sep, $words_array );
        }
    }

    return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
}

remove_filter( 'get_the_excerpt', 'wp_trim_excerpt');
add_filter( 'get_the_excerpt', 'wpse67498_wp_trim_excerpt' );
2
  • 2
    Okay, thank you. But now it seems, that I can’t shorten the excerpt anymore to 20 words and put a more button instead of [...]
    – Nitzki
    Commented Oct 8, 2012 at 16:03
  • 2
    So how can I now edit the excerpt_length and the excerpt_more? It doesn’t work any more.
    – Nitzki
    Commented Oct 9, 2012 at 10:45
3

wouldn't it be simpler to apply the_content filter to the excerpt?

i only use this occasionally, right within the template file:

$excerpt = apply_filters('the_content',  ( get_post(get_the_ID())->post_excerpt) );
echo $excerpt;
2
  • 1
    Brilliant! It worked for me Commented Mar 30, 2021 at 9:57
  • This looks like what I need. But where in the template does one put this, @diette? Thank you!
    – DWright
    Commented Jan 21, 2023 at 17:33
0

At the moment, it is possible to use the_excerpt() funtion to display the excerpt with line breaks. But if you like to return the result you can use for that purpose a function like this:

function get_the_excerpt_theme() {
    $excerpt = get_the_excerpt();
    $excerpt = apply_filters( 'the_excerpt', $excerpt );
    return $excerpt;
}

It applies a filters to the excerpt using apply_filters('the_excerpt', $excerpt ) like in the wp function the_excerpt() but returns the string without displaying it.

Also, if you like to allow only line breaks in the excerpt, you can add $excerpt = strip_tags($excerpt,'<br>') below the line apply_filters.

Hope it helps!

1
  • This does not work because it does not allow line breaks. Commented Mar 3, 2022 at 9:14
0

A simple solution is replacing line breaks before WordPress would replace them. I used an arbitrary selected character from the Unicode private area as it is not expected to appear in any content, also if it appears it is dedicated to be private use to indicate that handling is not standardised.

add_filter('wp_trim_words', function($text, $num_words, $more, $original_text) {
    static $filtering;
    if ( $filtering ) {
        return $text;
    }
    $filtering = true;
    
    // Random character from a unicode private use area
    $private_use_char = "\u{101425}";
    
    $text = str_replace( ["\n\r", "\n", "\r"], $private_use_char, $original_text);
    $text = wp_trim_words($text, $num_words, $more);
    $text = str_replace($private_use_char, "\n", $text); // or str_replace($private_use_char, "<br>", $text)
    
    $filtering = false;
    return $text;
}, 10, 4);

Note that this will result in "\n" characters in the output of the_excerpt() and get_the_excerpt(), so you probably want to call wpautop() on that before using it in HTML. Alternatively you can simply replace $private_use_char with <br> instead of \n as indicated by the comment.

-1

also could just use PHP's nl2br() function:

echo nl2br(get_the_excerpt());

-- or --

nl2br(the_excerpt());
3
  • This does not work. Commented Dec 15, 2020 at 20:16
  • Well latest version of wordpress seems to treat excerpt field like a normal post content field.. I just gave it a try on SandboxWordpress.com and new lines now return as separate paragraph tags. That said, im sure this did work in the past, or else id not have shared it. Not sure a downvote was needed, but glad to have this brought to my attention. Commented Dec 18, 2020 at 2:57
  • Well, I can remove the downvote, not sure what's the proper way, because despite the fact I believe this might have worked in the past, I have tried it and it does not any more, so I felt like I wasted my time, but on the other hand for sure no answer can stand right forever when the system it is for changes. So what would be the proper way of indicating that the answer is not useful any more, even while it might have been in the past? I'm open to suggestions. Please put a note in the answer indicating it does not work any more with the latest version of WP, and I'll remove the downvote. Deal? Commented Dec 18, 2020 at 11:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.