检查是否设置了自定义POST元后删除外部插件的操作

时间:2021-04-08 作者:Nick Li

Edit:The problem were 2 folds - somehow the order list I found before indicated wp_head was before wp_enqueue_scripts but that is not the case. Found another more updated one and it is actually right after. see the order of hooks here. Changing to get_header hook remove the action in my own class successfully.

I was unable to remove the External Plugin action because the remove_action() expect argument with the instance of the class, which the External Plugin did not expose the instance in any way. I found a snippet that remove action/filter based on given class name and method instead of the instance of the class and method. Obviously the drawback is action from multiple instances of the same class will be removed but that\'s not my concern. snippet in here Hope this help someone else as well.

我正在为外部插件编写一个附加组件,例如,如果页面/帖子存在自定义帖子元,请禁用/删除外部插件添加的某些操作,以及我自己的插件添加的操作。

我想从外部插件中删除的操作在类构造中调用。

class External_Plugin {
  function __construct() {
    add_action( \'wp_footer\', array( $this, \'inject-code\' ) );
  }
}
new External_Plugin();
我将支票post元代码挂接到wp\\U头上,如下所示

class My_Plugin {
  function __construct() {
    //check if dependency satisfied
    if (!class_exists(\'External_Plugin\')){
      add_action( \'admin_notices\', array( $this,\'display_dependency_error_notice\' ));
    }else{
      add_action( \'wp_enqueue_scripts\', array($this,\'my_plugin_enqueue_scripts\'));
      add_action( \'wp_head\', array( $this, \'check_post_meta\' ));
    }
  }

  function check_post_meta(){
    if (!is_admin()&&get_post_meta(get_queried_object_id(), \'fbcp_disable_chat\',true)){
      error_log(\'fired\');
      remove_action( \'wp_footer\', array(\'External_Plugin\',\'inject-code\',11 ));
      remove_action( \'wp_enqueue_scripts\', array($this,\'my_plugin_enqueue_scripts\'));
    }
  }
}
new My_Plugin()
我可以从日志中看到,我的if block in check\\u post\\u meta()确实被触发了,但外部插件的wp\\u footer操作和我的wp\\u enqueue\\u脚本挂钩操作都没有被删除。在我的理解中,wp\\u head hook已经在构建类之后了,因此我的remove\\u action()肯定是在我要删除的add\\u action()之后调用的,但在触发这些hook之前。有人能告诉我代码有什么问题,以及如何使用remove\\u action()吗?

P、 我也很困惑,什么时候我可以获取帖子ID来检索帖子元。。。为什么post id仅由wp\\U负责人提供?当我尝试init钩子时,我在那个阶段无法获得post ID。

Edit: Also found my answer to this question, should be able to use get_query_object_id() once after the parse_query hook, once again the order of WordPress hook in here.

1 个回复
SO网友:jdm2112

根据以下文件:remove_action() 函数名称和优先级必须match 连接函数的用法。你已经做出了一个常识性的假设,即应该使用更高的优先级来删除,但我认为这是问题的原因。

文档:https://developer.wordpress.org/reference/functions/remove_action/

To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.
更新删除操作语句以明确定义优先级10:

remove_action( \'wp_footer\', array(\'External_Plugin\',\'inject-code\', 10 ) );