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' ] );