I am using global $post
multiple times in a class. These are my doubts
- Is that a bad practice?
- Can it result in slow websites?
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; } }
I am using global $post
multiple times in a class. These are my doubts
- Is that a bad practice?
- Can it result in slow websites?
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; } }
1 Answer
Reset to default 1There'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' ] );
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745272419a4619830.html
function
keyword: eg,public function()
should bepublic function function_name()
. – Pat J Commented Aug 3, 2019 at 23:18