How to Attach a WordPress Hook to Private Method?

Explore the challenges with WordPress hooks when using an object-oriented approach. Learn how to use private methods as hooks callbacks. Click to dive in!

What is wrong with hooks in WordPress?

When using hooks, the handler needs to have a public accessor, which goes against encapsulation rules. That means that the handler can be accessed by clients even when it shouldn't be, potentially causing issues. Of course, it won't make any problems If I won't use this, but still - it breaks the rules that are important to me.

class Widgets
{
    public function __construct()
    {
        add_action('get_sidebar', [$this, 'addLinks']);
    }

    public function addLinks(): void
    {
        echo '<ul>...</ul>';
    }
}

How to use private method as a callback?

Are there any chances to prevent this? The first idea I'm thinking about is using anonymous function when I need to hook private function. There won't be a possibility to unhook the callback, but is this needed when it comes to private methods? 😎

class Widgets
{
    public function __construct()
    {
        add_action('get_sidebar', fn() => $this->addLinks());
    }

    private function addLinks(): void
    {
        echo '<ul>...</ul>';
    }
}
avatar

Looking for a developer who
truly cares about your business?

My team and I provide expert consultations, top-notch coding, and comprehensive audits to elevate your success.

Feedback

How satisfied you are after reading this article?