Jun 2, 2016

Remove Line Breaks in WordPress

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.

/**
 * Apply new wpautop filter to Press Release content
 */
function km_filter_press_release_content() {

	if ( ! is_singular( 'press-releases' ) ) {
		return;
	}

	remove_filter( 'the_content', 'wpautop' );
	add_filter( 'the_content', 'km_remove_wpautop_line_breaks' );
}
add_action( 'wp', 'km_filter_press_release_content' );

/**
 * Apply wpautop() to content and remove line breaks
 *
 * @param  string $content the_content().
 * @return string          the_content() with line breaks removed.
 */
function km_remove_wpautop_line_breaks( $content ) {
	return wpautop( $content, false );
}

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.

$string = '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.';

$content_without_line_breaks = preg_replace( '/(^|[^\n\r])[\r\n](?![\n\r])/', '$1 ', $string );

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.