Currently i am using the following generic flow for adding the shortcode for a plugin.
class MyPlugin {
private $myvar;
function baztag_func() {
print $this->myvar;
}
}
add_shortcode( 'baztag', array('MyPlugin', 'baztag_func') );
Now when this class and it’s method are called i get the following error.
Fatal error: Using $this when not in object context in …
(Line no is where i have printed the $this->myvar
)
Is this a problem on WordPress’s end or is there is something i’m doing wrong? It seems to be something really simple.
As the error says you need an instance of the class to use
$this
. There are at least three possibilities:Make everything static
But thatâs not real OOP anymore, just namespacing.
Create a real object first
This ⦠works. But you run into some obscure problems if anyone wants to replace the shortcode.
So add a method to provide the class instance:
Now, when someone wants to get the object instance, s/he just has to write:
Old solution: create the object in your class
You can use like this, shortcode inside the Class
If you want access shortcode content from another class. You can do like this.
Make sure that you make an instance of your class before using it unless you are sure it’s supposed to be called statically. When you call a method statically, you don’t use any instances and therefore it doesn’t have access to any member variables or methods.