2

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.

1 Answer 1

3

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 )
    {
        return;
    }

    if ( is_singular() )
    {
        $done = TRUE;
    }

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

Result

enter image description here

2
  • 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. Aug 24, 2012 at 14:22
  • @CNCPTS You can hijack native shortcodes easily. This will work with a wrapper too.
    – fuxia
    Aug 24, 2012 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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