最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hooks - Is there no concise way, a library maybe, to help with unhooking class functions and so on?

programmeradmin2浏览0评论

The WP_Filters API has a huge downside. It doesn't support unhooking of namespaced functions/class functions and so on to the best of my knowledge, but I refuse to believe that nor the core team, nor someone else came up with a way to do it.

I've read, searched but to no avail, the only things that are out there don't actually work.

An example of what I'm trying to achieve:

Class Test
{
    public function __construct()
    {
        add_action( 'init', [$this, 'testFunction'] );
    }

    public function testFunction()
    {
        echo 'Hey';
    }
}

new Test;

remove_action( 'init', ['Test', 'testFunction'] ) // and so on.

So, when we're actually hooking that function, what WP does internally is add_filter creates a unique hash for an object, in order to identify it by using _wp_filter_build_unique_id/, the problem with this function or rather PHP, is that it uses spl_object_hash to build that identity. This function doesn't give you an unique hash through requests, so, if you do remove_action( 'init', 'computedHashForTheObjectAndFunction' ), it will not work, because on the next request, it's gonna be a new one.

My assumption is that you can remove a function if you have that object's instance, but that's a rare, rare sight.

What can I do?


Edit: Yup, if you have access to the instance of the class in the same request, you can basically re-hash it to the same value and it will be able to remove the hook for you, so, inside my class, if I do remove_action( 'init', [$this, 'testFunction'], 10 );, it will work. Outside of that, though, is as I've said - impossible without an instance. Re-intializing the object just to get its identity is very, very bad because you might end up with unwanted functionality, so, that's out of the question.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论