Search code examples
phpwordpressclassoopextend

Extend Wordpress Plugin Class


I’m quite new to OOP, learned the basic idea and logic and now want to extend a wordpress plugin which is not intended for extending it (as far as I can tell):

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

So far so good. Now the code of my custom plugin:

class Custom_Plugin extends Main_Plugin {
    ...
}
new Custom_Plugin

From my understanding the object of the “main” plugin is initialized as well as my “child” plugin which means that the admin_notice.

Is there any way to create the “child” plugin correctly so that the “main” plugin is running and my custom plugin just adds some additional functionalities?


Solution

  • You don't really need to extends the Main_Plugin class, if you use class_exists to check if the main plugin class exists.

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

    You can split your main class, one for what you need on every load, one to extend.


    EDIT:

    There is other way to trigger some custom datas in other class

    In the Main_Plugin, you can define your own action/filter or use an existing one:

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

    In any custom plugin you'll be able to hook $notice_message easily:

    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;
    }