Function to show only first instance of shortcode

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.

Solutions Collecting From Web of "Function to show only first instance of shortcode"

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