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've written a shortcode plugin. Basically the plugin has the following structure:


class PL {

public static function setup() {
add_shortcode("myshortcode", array ( __CLASS__,"myshortcode_handler"));

public static function myshortcode_handler(
... some variable assignment?
   if (time the shortcode is invoked == 1) {
   else {
... some other code lines


I need to distinguish the case the shortcode is invoked for the first time or not. I think I have to declare some variable, but I do not know how and where I have to declare it.

share|improve this question
up vote 0 down vote accepted

I your shortcode callback myshortcode_handler() use a static variable:

function myshortcode_handler()
    static $first_call = TRUE;

    if ( ! $first_call )
        # callback was called earlier …

    # set it to FALSE after you have handled the condition.
    $first_call = FALSE;


Please do not misuse the global namespace for this: avoid constants, global variables and similar workarounds that might lead to unexpected conflicts.

share|improve this answer
What would happen in archive pages? If post #1 has a shortcode used and post #2 too, this would have another effect, right? I'm not sure if that's what the OP wants. – Camil Staps Feb 24 '13 at 21:40
@CamilStaps Why not? A second call is a second call. – toscho Feb 24 '13 at 21:42
I agree, but I can imagine that the OP wants only a second call in one post. – Camil Staps Feb 24 '13 at 21:43
Thank you for having done this remark. Indeed I need to know how many times the shortcode is invoked in a page. If the page is a post, then I need to know if the shortcode is invoked once or more. If the page displays many posts, I need to know if the shortcode is invoked once or more in all these posts or in their first lines which are contained on the page. Sorry to have not been clear. – Toc Feb 24 '13 at 22:40

There are a number of ways to do this. One of those ways is to define a constant the first time your callback runs.

if (!defined('myshortcode_check')) {
  // first time code
} else {
  // not the first time code

Should be fairly simple. That is a global, though, not post specific. This should work fine for single posts displays but may not be the behavior you want on post indexes. If that shortcode runs on any post in the index, it will define the constant.


share|improve this answer
Thank you. I will upvote your answer when I will reach the score allowing it. – Toc Feb 24 '13 at 22:38

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.