問題描述
我總是在 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。