unAutop: Undo WordPress wpautop

WordPress uses a PHP function called “wpautop” under the covers to convert your carefree blog post text into precise HTML. One of the most important things it does is wrap <p>…</p> tags around your paragraphs so you don’t have to…”WP automatic paragraphs” leads to the name “wpautop”. Good idea, right?

There are times when you just wish it wouldn’t do that. Have you ever found yourself with wpautop-ed text saved to your post? Do you wish you had an easy way to undo it?

Here’s a function that will undo the bulk of the damage caused by wpautop:

function unAutop( string $content ) : string {
    $content = mb_ereg_replace( '\n',     "",     $content, 'm' );
    $content = mb_ereg_replace( '<br>',   "\n",   $content, 'mi' );
    $content = mb_ereg_replace( '<br/>',  "\n",   $content, 'mi' );
    $content = mb_ereg_replace( '<br />', "\n",   $content, 'mi' );
    $content = mb_ereg_replace( '<p>',    "\n",   $content, 'mi' );
    $content = mb_ereg_replace( '</p>',   "\n\n", $content, 'mi' );
	 $content = mb_ereg_replace( '\n\n\n', "\n\n", $content, 'm' );

    return $content;
}

Leave a Comment