Remove whitespace at the end of posts?

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?

Related posts

Leave a Reply

4 comments

  1. 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.
    
  2. The ‘problem’ here is that wordpress converts ‘enters’ into paragraphs (< p >). Trailing and leading paragraphs result in large white spaces messing up your design. The wp (wysiwyg) editor is setup pretty spaciously and this often leads a user into believing the content is clean.

    Check this very simple plugin, Space Remover, it removes these unintended paragraphs and gives you control over this functionality as well. (in case you want to use that extra space on some posts/pages)

  3. 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( '/&nbsp;/', '☺', $content );
        $content = rtrim( $content, '☺' . " tnrx0B" );
        $content = preg_replace( '/☺/', '&nbsp;', $content );
        return $content;
    }
    add_filter( 'the_content', 'trim_post_trailing_whitespace', 0 );