WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to add a function to my theme to remove additional instances of a shortcode in a post.

First off I wonder if i'm approaching this wrong, but I have a theme that is drastically reformats the way a post is laid out. In the post we look for media and shortcode and then display them at the top of the page, basically stripping it from the content and placing it before the title.

The conditional statement checks for the existence of a featured image or a gallery shortcode, then prints it. The problem i'm running into is that the gallery is printed again in the the_content(). What i'd like to do is create a function to strip the shortcode after it's been printed the first time.

I'm aware of this hook remove_shortcode() but this will remove all instances of that shortcode where I only want to remove it after the first has been printed.

share|improve this question
up vote 2 down vote accepted

Add a static variable to the shortcode handler to check if the shortcode has been called already.

Sample code

add_shortcode( 'wpse62826', 'wpse_62826_shortcode' );

function wpse_62826_shortcode()
    static $done = FALSE;

    // Nothing to do.
    if ( $done )

    if ( is_singular() )
        $done = TRUE;

    return '<b>I run once on singular views!</b>';


enter image description here

share|improve this answer
I don't believe this will work because in this instance I need to use the existing shortcodes. This theme will be used on 20+ sites so it needs to check for the existing shortcodes, ie; [gallery], [embed] etc. – HjalmarCarlson Aug 24 '12 at 14:22
@CNCPTS You can hijack native shortcodes easily. This will work with a wrapper too. – toscho Aug 24 '12 at 15:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.