In the WordPress editor, lines that have a line break at the end of them will be turned into an HTML line break tag <br> then they are output on the site. This is often desirable, but not always. The functions below show how to remove line breaks in WordPress.

You can see that in the first function, I’m limiting this to only run on single posts of the ‘press-releases’ post type. Just┬áchange that conditional to apply to your use case and change all instances of ‘km_’ to whatever function prefix you’d like to use.

Regex

As an alternative, you could try applying a regular expression to the content like in the code below. This could be helpful for removing line breaks before importing a post into the database.

 

Output from the preg_replace above:

This is a new paragraph with arbitrarily inserted newlines at a certain width. To keep these from turning into <br>s, we want to replace them the right way.

When there is a double new-line, then we know that it really is a new paragraph, and it is OK to keep both newlines together.

2 comments

  1. Peter Bates September 30, 2018 at 7:52 am

    Reply

    Where do you put this code?

    • Kellen Mace October 1, 2018 at 11:12 am

      Reply

      This code can go in a custom plugin or in the functions.php file of your theme. Please note though, that if you use a theme from wordpress.org or a 3rd party theme seller, the functions.php file may be overwritten the next time your update your theme. So if that’s the case, I would recommend creating a small, 1-file plugin with that code in it. Here’s a how-to guide: https://www.smashingmagazine.com/2011/09/how-to-create-a-wordpress-plugin/. Best of luck!

Leave a reply

Your email address will not be published. Required fields are marked *