Zahid Saeed
Zahid Saeed

Reputation: 1181

Is there any difference between a class method and a regular function?

I'm trying to learn wordpress to create my wordpress themes. But the problem is, whenever I try to load my css files by using the wp_enqueue_style() inside a class then my wordpress admin area just breaks up. What I mean by breaking is that, it's js file fails to load due to which it's coloring scheme turns from blue to red and functionality of buttons like "Screen Options" or "Help" stops working.

Here is the working code:

function wp_custom_styles(){
    wp_enqueue_style("bootstrap_css", get_template_directory_uri() . "/css/bootstrap.min.css");
    wp_enqueue_style("style_css", get_stylesheet_uri());
 }
 add_action("wp_enqueue_scripts", "wp_custom_styles");

But if I use this:

class wp_theme_preparation{
    public function __construct(){
        add_action("wp_enqueue_scripts", $this->add_theme_styles());
    }
    public function add_theme_styles(){
        wp_enqueue_style("bootstrap_css", get_template_directory_uri() . "/css/bootstrap.min.css");
        wp_enqueue_style("style_css", get_stylesheet_uri());
    }
}
$instance = new wp_theme_preparation();

The admin area crashes. And it ends like this: As you can see from the image I clicked on the "Screen Options" button but it doesn't work.

So my question is what is the difference between these two codes ? Why the first piece of code is working and second isn't when both of them are just calling a function ?

Upvotes: 0

Views: 83

Answers (1)

Kenney
Kenney

Reputation: 9093

To register an action that is a method, you should use

add_action("wp_enqueue_scripts", array( $this, 'add_theme_styles') );

See the documentation (particularly the 'Using with a class` section).

UPDATE

Your original code

add_action("wp_enqueue_scripts", $this->add_theme_styles());

attempts to register the return value of calling $this->add_theme_styles() as a callback, not what you intended.

WordPress makes use of PHP's call_user_func, which expects a callable argument. From that page:

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

That last sentence comes down to passing array( $objectInstance, 'method_name' ) as the callback.

Upvotes: 1

Related Questions