Fix WordPress excerpt to show line breaks

Categories: CMS, Wordpress

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

Reference:

https://wordpress.stackexchange.com/questions/67498/how-to-include-line-breaks-in-the-excerpt

«
»