A few weeks ago, I’ve made a total revamp of my website (the one you’re on). The old one was 6 years old, and for some obscure reasons I used shortcodes to add columns or deviders to my content. During the revamp, I had to remove all this shortcodes, but I didn’t wan’t to search en edit all posts manually (I’ve more than an hundred posts on the blog), so I wrote a very simple function to do that.
I firstly tried to use the strip_shortcodes with strip_shortcodes_tagnames filter, but the problem is that this hook removes the shortcode AND it content. So in my case, it removed the columns shortcode and the columns content (eg: [column]Will be removed too[/column]). Not accurate anought for my need.
I finally decided to make it simple and use a REGEX with the content_save_pre hook which is fired right before saving the content in the database. Doing this, I only have to bulk update my posts to stripes all the shortcodes I don’t want anymore.
All you have to do is to provide the list of shortcodes you don’t want anymore by filling the $tags_to_remove array.
add_action( 'content_save_pre', 'bweb_remove_shortcodes', 9, 2 ); function bweb_remove_shortcodes( $content ) { $tags_to_remove = array( 'shortcode_to_remove_1', 'shortcode_to_remove_2', ); foreach( $tags_to_remove as $tag ){ $content = preg_replace('#\[[^\[]*' . $tag . '[^\]]*\]#', '', $content ); } return $content; }
I’ve done bulk actions with 30 posts each time without an issue, but it also works when editing a single post. I suggest you to do that first to make sure the function is working properly for you. When you’re done, simply remove the function 😉
Don’t use this function on your stage site!
HI mate, that saves my day, thanks for that.
Thanks!
This really helped me to start working on something similar.
This would be the same but avoiding the loop
function bweb_remove_shortcodes( $content ) {
$tags_to_remove = [
‘shortcode_to_remove_1’,
‘shortcode_to_remove_2’,
];
$tagsRegex = ‘(‘ . join( ‘|’, $tags_to_remove ) . ‘)’;
return preg_replace(‘#\[[^\[]*’ . $tagsRegex . ‘[^\]]*\]#’, ”, $content );
}