扩展 Wordpress 插件 Class

Extend Wordpress Plugin Class

我对 OOP 很陌生,了解了基本的思想和逻辑,现在想扩展一个 wordpress 插件,它不是为了扩展它而设计的(据我所知):

class Main_Plugin {
    ...
    function __construct() {
        add_action('admin_notice', array($this, 'somefunction');
    }
    ...
}
enter code here
new Main_plugin

到目前为止一切顺利。现在是我自定义插件的代码:

class Custom_Plugin extends Main_Plugin {
    ...
}
new Custom_Plugin

根据我的理解,“主”插件的对象以及我的“子”插件都已初始化,这意味着 admin_notice.

有什么方法可以正确创建“子”插件,使“主”插件成为 运行 而我的自定义插件只是添加了一些额外的功能?

您的想法是正确的,但在 Wordpress 中最好不要使用相同的动作名称来制作不同的插件。随意扩展 Main_Plugin class 但请将您的操作名称更改为另一个名称并在您的模板中使用它。因此,您的代码将如下所示:

class Custom_Plugin extends Main_Plugin {
    function __construct() {
      add_action('admin_notice_v2', array($this, 'somefunction');
    }
}
new Custom_Plugin

如果您想完全覆盖之前的操作,请删除之前的操作并按照此处所述添加您的操作:https://wordpress.stackexchange.com/questions/40456/how-to-override-existing-plugin-action-with-new-action 如果您想扩展操作,那么只需从您的操作中调用父操作

如果您使用 class_exists 检查主插件 class 是否存在,您实际上不需要扩展 Main_Plugin class。

 if(class_exists('Main_Plugin')){
      new Custom_Plugin;
 }

您可以拆分主 class,一个用于每次负载所需的,一个用于扩展。


编辑:

还有其他方法可以在其他 class

中触发一些自定义数据

Main_Plugin 中,您可以定义自己的 action/filter 或使用现有的:

 $notice_message = apply_filters('custom_notice', $screen, $notice_class, $notice_message);// you need to define parameters before

在任何自定义插件中,您都可以轻松挂钩 $notice_message:

public function __construct(){
    add_filter('custom_notice', array($this, 'get_notice'), 10, 3); 
}
public function get_notice($screen, $notice_class, $notice_message){
    $notice_message = __('New notice', 'txt-domain');
    return $notice_message;
}