0

I contain all my short-codes in (the equivalent of) functions.php. I want to have one short-code function share information in an object, and another able to access that object. The shortcodes may or may not be on a page together.

I was thinking a unique global $obj rather than using global $post.

What is the 'correct' method in Wordpress?

  • depending on your specific implementation needs, global objects are not necessarily a bad thing (many plugins are predicated on this design pattern). of course any shortcode you make rely on this object, while not properly function if the object does not exist. IF that is ok with you and your design needs, then go for it? – Brandt Solovij Dec 11 '14 at 16:48
1

The correct way is not to do it. Shortcodes are supposed to be self contained and represent an insertion point to some complicated HTML that is harder to get right or due to security permissions is impossible to insert in its pure HTML form.

Globals are hated magic when you write proper code, now think about plain text, how exactly the non technical writer can even guess that one shortcode is depending on the other, and what will be the result of removing one of them?

if the second shortcode needs to know the attributes passed to the first, just document that the user should pass the same parameters to both.

  • If I cannot do this, I will need to query the database twice. If I query twice using the same arguments (so getting the same results) does WP store the initial result or does it really query the database twice? – myol Dec 11 '14 at 14:00
  • 1
    @myol It depends on what exactly you do, but if you avoid writing your own SQL, and use the higher level functions like get_post_meta then the returned value should be cached and returned from the memory on a second call with the same parameters. BTW, I didn't mean you should not cache the results of whatever the first short code do, if it will improve performance then sure use a global or whatever you fancy to get it done, just don't create dependencies that are hard to understand/see when looking at the content. – Mark Kaplun Dec 11 '14 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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