问题描述

我总是在 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 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。