問題描述
我總是在 Wordpress 外掛上為客戶做更改。但是如果外掛被更新,這些更改總是會有丟失的危險。
有沒有辦法在 Wordpress 中為另一個外掛建立一個外掛?每個外掛更新後,是否有一種保留更改的方法或 re-apply 。
最佳解決方案
我認為最好的辦法是透過動作和過濾器,像我們擴充套件 WordPress 核心本身。
其他選項就像 @helgatheviking 指出,如果外掛是類,你可以擴充套件它。
遺憾的是,並不是所有的外掛開發人員都用他們的程式碼提供了有用的過濾器和操作,大多數情況下外掛不是以 OOP 方式編寫的。只有儲存您對外掛更新的修改方法,才能建立原始外掛的副本,更改外掛名稱。我通常以原始名稱為例,例如 Mamaduka Twitter Connect
,但是使用此解決方案,您需要手動更新原始外掛的程式碼。
如果您認為該外掛需要更多的過濾器/操作,您可以聯絡作者並要求他將這些鉤子包含在核心中。
次佳解決方案
一個簡單的方法是在外掛中定義你可以掛鉤的自定義鉤子。 in-built 掛鉤系統允許您建立自己的鉤子,然後像普通的 Wordpress 鉤子一樣繫結到它們上。 WordPress Codex 對 do_action 功能有很好的例子和解釋,以及如何使用它來建立自定義鉤子。外掛和主題開發人員在 Wordpress 中被嚴重忽視的功能。
我堅信,掛鉤系統是您需要開發可以透過其他外掛擴充套件的外掛,但正如我所說的 90%的 Wordpress 開發人員所忽視的那樣。
見下面的例子 (取自 Wordpress Codex 連結):
<?php
# ======= Somewhere in a (mu-)plugin, theme or the core ======= #
/**
* You can have as many arguments as you want,
* but your callback function and the add_action call need to agree in number of arguments.
* Note: `add_action` above has 2 and 'i_am_hook' accepts 2.
* You will find action hooks like these in a lot of themes & plugins and in many place @core
* @see: http://codex.wordpress.org/Plugin_API/Action_Reference
*/
// Define the arguments for the action hook
$a = array(
'eye patch' => 'yes'
,'parrot' => true
,'wooden leg' => (int) 1
);
$b = 'And hook said: "I ate ice cream with peter pan."';
// Defines the action hook named 'i_am_hook'
do_action( 'i_am_hook', $a, $b );
# ======= inside for eg. your functions.php file ======= #
/**
* Define callback function
* Inside this function you can do whatever you can imagine
* with the variables that are loaded in the do_action() call above.
*/
function who_is_hook( $a, $b )
{
echo '<code>';
print_r( $a ); // `print_r` the array data inside the 1st argument
echo '</code>';
echo '<br />'.$b; // echo linebreak and value of 2nd argument
}
// then add it to the action hook, matching the defined number (2) of arguments in do_action
// see [http://codex.wordpress.org/Function_Reference/add_action] in the Codex
// add_action( $tag, $function_to_add, $priority, $accepted_args );
add_action( 'i_am_hook', 'who_is_hook', 10, 2 );
# ======= output that you see in the browser ======= #
Array (
['eye patch'] => 'yes'
['parrot'] => true
['wooden leg'] => 1
)
And hook said: "I ate ice cream with peter pan."
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。