How to get excerpt correctly formatted


I’m using a theme that use the_excerpt() function to show the excerpt of the post.

All posts have not set custom excerpt, so the_excerpt() returns a piece of post content.

In some post first paragraph contains a <br>, for example:

<p>My new question is:<br>why words are not separated by a white space?</p>

The text rendered is:

My new question is:why words are not separated by a white space?

Following this post I implemented this solution:

function my_excerpt($text = '', $raw_excerpt = '') {
    add_filter('the_content', 'my_content', 6);

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

    remove_filter('the_content', 'my_content', 6);
    return $text;
remove_filter( 'get_the_excerpt', 'wp_trim_excerpt');
add_filter( 'get_the_excerpt', 'my_excerpt');

function my_content($text)
    return str_replace( '<br>', ' ', $text );

And this works, but I have two questions:

  1. Why the_excerpt() doesn’t substitute <br> with space?
  2. Is there a better way to achieve this result?

Also, I’m quite new to wordpress development, any suggestions to improve my code are welcome.

Lety 3 months 0 Answers 8 views 0

Leave an answer