Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

My writer has a tendency to add extra newlines (Enter key) and spaces (space bar) at the ends of posts. Sometimes this results in inches of extra whitespace onscreen!

Is there a way I can make sure extra trailing whitespace is removed when he hits "Update" in the Wordpress post editor?

share|improve this question
You could threaten him... –  markcbain May 25 at 7:17

3 Answers 3

Quick guess would be:

add_filter('content_save_pre', 'trim');

Add to functions.php of theme or wherever is appropriate in your site.

share|improve this answer
Doesn't work. Maybe it's because the post is still full of trailing  s ? –  a paid nerd Aug 30 '11 at 4:16
@a paid nerd likely that. trim() only removes true whitespace. It worked for me in quick test, but I used HTML editor. Likely your writer is using visual one that encodes spaces. You will need to hook your own function that will delete (or convert to regular spaces before trim) those entities. –  Rarst Aug 30 '11 at 8:49

This will stop the trailing non-breaking spaces from displaying without actually modifying the post in the database when added to functions.php (or wherever your theme stores user added functions).

function trim_post_trailing_whitespace($content){   
// use preg_replace to convert   into an unused character "☺" (ALT 1)
// then use rtrim to remove trailing unused character(s) "☺"
// now use rtrim again to remove trailing whitespace 
// now convert unused character(s) "☺" back into   in case used elsewhere
// Return

    $content = preg_replace("/ /", "☺", $content);
    $content = rtrim($content, "☺");
    $content = rtrim($content);
    $content = preg_replace("/☺/", " ", $content);
    return $content;

/* All the above simplified into a single equation  
    return preg_replace("/☺/", " ", rtrim(rtrim(preg_replace("/ /", "☺", $content), "☺")));   

add_filter('the_content', 'trim_post_trailing_whitespace', 0);
// The '0' priority means do this first.
share|improve this answer

If you want to remove not only one but several trailing non-breaking spaces, you could use a variation of UncaJoes code which also uses the default php rtrim charlist.

function trim_post_trailing_whitespace( $content ) {
    $content = preg_replace( '/ /', '☺', $content );
    $content = rtrim( $content, '☺' . " \t\n\r\0\x0B" );
    $content = preg_replace( '/☺/', ' ', $content );
    return $content;
add_filter( 'the_content', 'trim_post_trailing_whitespace', 0 );
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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