add_action in wp_head accessible from class

You’re using the static class method call when supplying a callable/callback to add_action():

add_action( 'wp_head', array( 'test_class', 'greeting_head' ) );

So you should make the greeting_head() a static method in your test_class class. But you’d also need to make the greeting() a static method:

class test_class {

    public static function greeting() {
        echo 'Howdy! Test is successful!';

    public static function greeting_head() {

And unless you use a singleton pattern, you’d need to use the self keyword to access methods and properties from a static method; for example, in the above code, you could see that I’m using self::greeting() and not $this->greeting().

But I wouldn’t suggest using static class methods unless absolutely necessary, and you can just leave your class as it is now — except, use $this->greeting() in the greeting_head() method — and use the object method call when supplying the add_action() callback:

class test_class {

    function greeting() {
        echo 'Howdy! Test is successful!';

    function greeting_head() {

$test_class = new test_class;

add_action( 'wp_head', array( $test_class, 'greeting_head' ) );

This answer doesn’t cover everything about classes in PHP, but I hope it helps you; and if you need further guide, you can search on Stack Overflow or even here on WordPress Stack Exchange.. =)


For completeness,

  1. You’re getting this error because you’re trying to access a global function named greeting which obviously doesn’t exist since PHP threw that error:

    greeting() is undefined.

  2. How to access if from outside test_class?” — Use the $this keyword: $this->greeting(), just as @Adnane and I mentioned in our original answer. Or use self::greeting() as I stated in my original answer.

    (Update)if from outside test_class” — Actually, the proper question should be, “how to access the greeting() method from another method in the same class” because you are actually calling test_class::greeting() from test_class::greeting_head(). 🙂

  3. And your code as in the current question would result in the following PHP notice: (see the add_action() note above)

    Non-static method test_class::greeting_head() should not be called

    In addition, you’d get the following PHP fatal error if you simply use $this in your original greeting_head():

    Uncaught Error: Using $this when not in object context

And for this question:

Can you point me to some documentation on the pros and cons of using
static class methods?