Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress - Remove empty p tags for custom shortcodes
<?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;
}
@ghost

This comment has been minimized.

Copy link

@ghost ghost commented Feb 18, 2014

Hello, any newer option for removing empty p? I can't get theme accepted on themeforest with this code inside.

@dtbaker

This comment has been minimized.

Copy link

@dtbaker dtbaker commented Feb 20, 2014

A friend of mine also had his theme rejected using this, but it might still be possible if it is explained, http://themeforest.net/forums/thread/how-to-add-shortcodes-in-wp-themes-without-being-rejected/98804#993635

@ash-f

This comment has been minimized.

Copy link

@ash-f ash-f commented Oct 3, 2017

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);

@cecowe

This comment has been minimized.

Copy link

@cecowe cecowe commented Jul 10, 2018

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment