0

I am wondering whether using global $post is a 'best practice' when it is necessary to get the $post within a callback function triggered by an action hook.

The code would be:

class myPlugin {

    public function __construct() {
        add_action('wp', array( $this, 'init'));
    }

    public function init() {

        global $post;

        if (isset($post)) {
            // do something
        }

    }
}

I've tried to:

  • Call the init function with $post as argument; and

  • What is posted here

But, none of the options work.

How safe would be to use global? Let's say that the 'do something' is a custom WP Query, which may change the value of $post, having declared it global has the potential of doing something unexpected right?

Is there a better way?

Cheers.

0

Short answer "no", using globals is never a best practice, indicates that you might be trying to do something in the wrong place, and should be left as a last resort.

In your snippet for example you have no idea who set the $post, was it set in the loop or outside it, was it a single post loop, etc.

As a rule of thumb never use globals, they are just evil.

  • Thanks for the reply. The snippet is called when plugin is initialised, so it is outside the loop (I think). The main plugin file, let’s say myPlugin.php creates an instance of the class e.g. $instance = new myPlugin(). This happens for each wordpress request. Let’s say that the //do something is adding hooks depending on the requested page, you would then need access to the $post, e.g. if (isset($post) && $post→post_name = ‘page_slug’) { add_hooks } – Pisuke Soramame Jun 13 '17 at 12:49
  • as i said, it doesn't matter where you use it, you have no idea when and where a value was set to it. If you need the first post in a loop you should rewind the loop and call the_post. Then most likely you can call API functions that work on the "current" post without the need to actually care about the variable itself. – Mark Kaplun Jun 13 '17 at 13:05

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.