[wp-hackers] How to prevent multiple processing of shortcodes?
otto at ottodestruct.com
Mon Jul 9 17:01:37 UTC 2012
On Mon, Jul 9, 2012 at 9:43 AM, Mike Walsh <mpwalsh8 at gmail.com> wrote:
> I am looking for some advice on how to prevent a shortcode from being
> processed multiple times. I am trying to help a user of my WordPress
> Google Form plugin and figured out that another plugin is calling
> do_shortcode() as part of the wp_head action which causes my shortcode to
> be processed twice. Because my shortcode uses the WordPress HTTP API to
> submit form data to Google Forms, processing the short code twice messes
> things up. I am not sure if running do_shortcode() as part of wp_head is a
> bad idea, it seems to me like it is but I am sure there is a good reason
> for it. So I am trying to update my plugin to deal with this situation.
> Any recommendations or idea? I thought about trying to use a transient to
> track when wp_remote_post() is called which might work for simple forms but
> since many Google Forms have more than one page, wp_remote_post() is called
> more than once and in theory could be called in unknown number of times
> since Google Forms support going back and forth through the pages.
Bottom line: You're doing it wrong. Rewrite your plugin such that the
shortcode isn't doing that.
Shortcodes are meant to be inside of the post-content, and to return
some HTML or whatever that will replace the shortcode itself inside
that content. *It is going to be run multiple times on the page, and
you should design it such that it does that correctly*.
A shortcode is basically the same thing as a filter. It should not
have any side effects. Having the shortcode send data to some Google
Forms thing somewhere is a *big* side effect, and it is simply not
something a shortcode should ever do.
Now, if you're submitting data, then you need to move the part that
does the actual submit outside the shortcode itself. I'll give you an
example. Say you have a shortcode to make a contact form on the page.
The shortcode function should:
- Output a form, and
- Do nothing else.
Now, you might ask, how do I get the results of that form? Well, the
form has to submit the data to somewhere, and it's probably to this
same page. So, I can hook onto the init action hook, recognize when
the form was submitted, and act accordingly. The important bit here is
that the "init" action hook is an *action* hook. You can do things
(like actions) on action hooks. The "init" hook isn't going to run
twice. The shortcode isn't an action hook, it shouldn't "do" anything
other than return that form. Leave doing stuff to action hooks.
More information about the wp-hackers