0

I've written a shortcode plugin. Basically the plugin has the following structure:

PL::setup();

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.

2 Answers 2

0

In 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;

    return;
}

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

4
  • 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.
    – user26607
    Commented Feb 24, 2013 at 21:40
  • @CamilStaps Why not? A second call is a second call.
    – fuxia
    Commented Feb 24, 2013 at 21:42
  • I agree, but I can imagine that the OP wants only a second call in one post.
    – user26607
    Commented Feb 24, 2013 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
    Commented Feb 24, 2013 at 22:40
1

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
  define('myshortcode_check',true);
} 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.

http://php.net/manual/en/function.defined.php
http://php.net/manual/en/function.define.php

1
  • Thank you. I will upvote your answer when I will reach the score allowing it.
    – Toc
    Commented Feb 24, 2013 at 22:38

Your Answer

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

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