2016-11-17 99 views
1

我很新的OOP,學會了基本思路和邏輯,現在要延長其不用於擴展它(據我可以告訴)一個WordPress插件:擴展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

有什麼方法可以正確創建「子」插件,以便「主」插件正在運行,並且我的自定義插件只是添加了一些附加功能?

回答

1

如果您使用class_exists來檢查主插件類是否存在,那麼您並不需要擴展Main_Plugin類。

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

你可以拆分你的主類,一個用於你需要的每個負載,一個用於擴展。

編輯:

還有其他的方式來觸發其他類

一些定製DATAS在Main_Plugin,你可以定義自己的動作/過濾器或使用現有的一個:

$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; 
} 
+0

好吧,但如果主已包含另一個功能,如: 'if($ pagenow ==='wp-login.php'){ global $ error,$ interim_login,$ action,$ user_login; @require_once ABSPATH。 'WP-的login.php'; 死亡; }' 當我的插件在主要權限之後運行時,將無法更改此行爲?如果情況不符合我的條件,我將不得不編寫一個在主插件之前運行的插件,以便讓主插件完成剩下的工作。 – adrianwell

+0

是的,爲什麼我告訴你分班 – Benoti

+0

好的謝謝。即使我不想更改原始插件(更新覆蓋等),這對我有幫助。 – adrianwell

0

你認爲在正確的方向,但在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 如果你想只延長行動,那麼從你的動作調用父動作

+0

對不起但我不認爲這會幫助我...插件不會影響我的模板,並且在我看來,wordpress動作鉤子意味着多次使用。讓我以不同的方式解釋:我可以使用remove_action函數來阻止我的插件顯示主插件的admin_notive兩次。但是所有其他函數會在我的插件正確之前初始化主插件的對象時再次運行?有沒有辦法擴展主插件並單獨初始化擴展對象? – adrianwell