Last active
April 3, 2025 18:18
-
-
Save bitfade/4555047 to your computer and use it in GitHub Desktop.
WordPress - Remove empty p tags for custom shortcodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter("the_content", "the_content_filter"); | |
function the_content_filter($content) { | |
// array of custom shortcodes requiring the fix | |
$block = join("|",array("col","shortcode2","shortcode3")); | |
// opening tag | |
$rep = preg_replace("/(<p>)?\[($block)(\s[^\]]+)?\](<\/p>|<br \/>)?/","[$2$3]",$content); | |
// closing tag | |
$rep = preg_replace("/(<p>)?\[\/($block)](<\/p>|<br \/>)?/","[/$2]",$rep); | |
return $rep; | |
} |
Hey,
I have a child theme active right now. Should I add this snippet to functions of the child theme or the parent theme?
How may I add the code, in the end of the .php or?
Is this still working? I am having that issue
Is this still working? I am having that issue
i used this code
function clean_shortcodes($content) {
// List of shortcodes to process
$shortcodes = [
'item',
'itemalt'
];
// Process each shortcode
$content = array_reduce($shortcodes, function($carry, $shortcode) use ($content) {
if (has_shortcode($carry, $shortcode)) {
return preg_replace(
"/(?:<p>|<br \/>)*\[(\/?{$shortcode})([^\]]*)\](?:<\/p>|<br \/>)*\s*/i",
"[$1$2]",
$carry
);
}
return $carry;
}, $content);
return $content;
}
add_filter('the_content', 'clean_shortcodes', 10);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interesting.
But shouldn't it be content_save_pre or something rather than the_content that works when saving posts?
So it will put less server loads.
function my_sanitize_content($value){ $value = preg_replace("/<p>(\[[^<]+?)<\/p>/u","$1",$value); $value = preg_replace("/<p>(\[[^<]+?)<br \/>/u","$1<p>",$value); return $value; } add_filter('content_save_pre','my_sanitize_content',10,1);