Skip to content

Instantly share code, notes, and snippets.

@vades
Last active May 21, 2019 06:38
Show Gist options
  • Save vades/6e59f26223c4b21ba44d6e4e6755c6d2 to your computer and use it in GitHub Desktop.
Save vades/6e59f26223c4b21ba44d6e4e6755c6d2 to your computer and use it in GitHub Desktop.
Remove empty p tags from WordPress posts

Remove empty p tags from WordPress posts

function wps_clear_content($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);
}

Usage

add_filter('the_content', 'wps_clear_content', 20, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment