Lego2012
12/13/2016 - 2:44 PM

Remove empty p tags and nbsp from the content

Remove empty p tags and nbsp from the content

<?php
//* Do NOT include the opening php tag shown above. Copy the code shown below.

/**
 * Remove empty p tags and nbsp from the content
 *
 * @author  Tyrel Kelsey
 * @link     https://gist.github.com/ninnypants/1668216
 *
 * @return  mixed
 */
add_filter( 'the_content', 'll_remove_empty_p', 20, 1 );
function ll_remove_empty_p( $content ){
    // clean up p tags around block elements
    $content = preg_replace( array(
        '#<p>\s*<(div|aside|section|article|header|footer)#',
        '#</(div|aside|section|article|header|footer)>\s*</p>#',
        '#</(div|aside|section|article|header|footer)>\s*<br ?/?>#',
        '#<(div|aside|section|article|header|footer)(.*?)>\s*</p>#',
        '#<p>\s*</(div|aside|section|article|header|footer)#',
    ), array(
        '<$1',
        '</$1>',
        '</$1>',
        '<$1$2>',
        '</$1',
    ), $content );
    return preg_replace('#<p>(\s|&nbsp;)*+(<br\s*/*>)*(\s|&nbsp;)*</p>#i', '', $content);
}