扩展Wordpress插件类


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 .

是否有任何方法可以正确创建"子"插件,以便"主"插件正在运行,而我的自定义插件只是添加了一些额外的功能?

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

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

你可以拆分你的主类,一个用于每次加载,一个用于扩展。


编辑:

在其他类

中有其他触发自定义数据的方法

Main_Plugin中,您可以定义自己的动作/过滤器或使用现有的:

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

在任何自定义插件中,你都可以很容易地钩子$ notife_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;
}

你认为方向正确,但在Wordpress中最好不要使用相同的操作名称做不同的插件。可以随意扩展Main_Plugin类,但请将操作名称更改为另一个并在模板中使用它。因此,您的代码将看起来像这样:

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如果你想扩展这个动作只需从action

中调用parent action