Write a WordPress function that removes a shortcode from all posts of a WordPress post type
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need a function that will search WordPress posts of a custom post-type content_shortcode and remove any instances of a shortcode content-shortcode.

The shortcode is self-closing (i.e. it will only ever appear in posts as: [content-shortcode]), but it may or may not contain an arbitrary number of attributes (such as [content-shortcode post-id="9"]).

awarded to tannhauser

Crowdsource coding tasks.

1 Solution

Winning solution

Here is a generic function for removing any occurences of a specified self-closing shortcode with name shortcode_name from posts with type post_type

function remove_shortcode_from($post_type, $shortcode_name)
    global $wpdb;
    $res = $wpdb->get_results($wpdb->prepare(
        "SELECT * FROM $wpdb->posts WHERE `post_type`=%s",

    foreach ($res as $k => $v) {
        $regex = "/\\[${shortcode_name}[^\\]]*\\]/u";

        if(preg_match($regex ,$v->post_content)){

            $content = preg_replace($regex, "", $v->post_content);

                $wpdb->prepare("UPDATE $wpdb->posts SET post_content=%s WHERE ID=%d",
                    $content, $v->ID));

In your case, call it:
remove_shortcode_from('content_shortcode','content-shortcode');, or wrap this call into another function.