Question

I am using global $post multiple times in a class. These are my doubts

  1. Is that a bad practice?
  2. Can it result in slow websites?
  3. What's the proper way to use it inside a class

    class Test{
        public function(){
            global $post;
        }
    
        public function2(){
            global $post;
        }
    
        public function3(){
            global $post;
        }
    }
    
Was it helpful?

Solution

There's nothing wrong with using the global $post variable per se, although there are people who will say that using global variables is always bad. But since you're using it multiple times in the same object, it would be better to just get the post once and store it in a class property.

I prefer using the WordPress get_post() function because it looks cleaner and get_post() does some stuff if the global $post variable isn't a WP_Post object. Using the global $post variable multiple times in a class will not slow down your site though, if that's your main worry.

So my class might look something like this:

class Test {
  protected $post;
  public function __construct() {
    $this->post = \get_post();
  }
  public function fizzbuzz() {
    //* Use $this->post instead of global $post
  }
  ... and etc. Mainly etc.
}

If you're looking to modify the global $post object, a better method would be to use the the_post action hook to access the $post object immediately after it is setup.

class Test {
  public function the_post( $post_object ) {
    //* Do something useful with the post object
  }
}
add_action( 'the_post', [ new Test(), 'the_post' ] );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top