在WordPress中触发事件的替代方法

In the first part of this series on the WordPress hook system, we learned about the WordPress hook system and the two types of hooks actions and filters alongside some code examples of how they work.

WordPress钩子系统的本系列第一部分中 ,我们了解了WordPress钩子系统以及两种类型的钩子actionsfilters以及一些有关它们如何工作的代码示例。

In this second part of this series, we’ll be learning about alternative ways of triggering events in WordPress and how to hook static and non-static class methods to actions and filters.

在本系列的第二部分中,我们将学习在WordPress中触发事件的替代方法,以及如何将静态和非静态类方法挂钩到actionsfilters

WordPress Hooks

In the previous article, I made the following statement:

在上一篇文章中,我做了以下声明:

At various stages of WordPress execution, a large number of events are triggered commonly using the do_actions() and apply_filters() PHP functions. These events can be subscribed or hooked to via add_action() and add_filter().

在WordPress执行的各个阶段,通常会使用do_actions()和apply_filters()PHP函数来触发大量事件。 这些事件可以通过add_action()和add_filter()进行订阅或挂接。

Take note of my use of the word “commonly”. There are other ways events can be triggered. We’ll explore that in the second part of this tutorial.

注意我使用“ commonly”一词。 还有其他触发事件的方法。 我们将在本教程的第二部分中对此进行探讨。

The other ways events can be triggered are via do_action_ref_array() function for action hooks and apply_filters_ref_array() for filter hooks.

可以触发事件的其他方式是通过do_action_ref_array()函数(用于action钩)和apply_filters_ref_array()用于filter钩)。

Both do_action(), do_action_ref_array() and apply_filters(), apply_filters_ref_array() are the same in that each pair are used to execute functions hooked to specific action and filter respectively. The difference is in how they specify their argument.

do_action()do_action_ref_array()apply_filters()apply_filters_ref_array()都是相同的,因为每对分别用于执行挂钩到特定动作和过滤器的函数。 不同之处在于他们如何指定论据。

Unlike do_action() and apply_filters(), do_action_ref_array() and apply_filters_ref_array() specifies their argument as an array.

do_action()apply_filters()do_action_ref_array()apply_filters_ref_array()其参数指定为数组。

Let’s see some code examples to better understand how they work.

让我们看一些代码示例,以更好地理解它们的工作方式。

程式码范例 (Code Examples)

The action user_profile_update_errors is fired in WordPress before user profile update errors are returned and the profile is updated.

在返回用户配置文件更新错误并更新配置文件之前,会在WordPress中触发user_profile_update_errors操作。

Say you added a custom field to the WordPress user profile and wanted to validate its input before WordPress saves the data to the database. This is the hook you need.

假设您向WordPress用户配置文件中添加了一个自定义字段,并想在WordPress将数据保存到数据库之前验证其输入。 这是您需要的钩子。

Here is how it is defined in WordPress core.

这是在WordPress核心中定义的方式。

/**
     * Fires before user profile update errors are returned.
     *
     * @since 2.8.0
     *
     * @param WP_Error &$errors WP_Error object, passed by reference.
     * @param bool     $update  Whether this is a user update.
     * @param WP_User  &$user   WP_User object, passed by reference.
     */
    do_action_ref_array( 'user_profile_update_errors', array( &$errors, $update, &$user ) );

The code below ensures a custom profile field named city (where users can enter their cities) is not left empty. If it is, an error to that effect will be displayed.

下面的代码可确保自定义配置文件字段“城市”(用户可以在其中输入城市)不会留空。 如果是这样,将显示该错误。

add_action( 'user_profile_update_errors', function ( $errors, $update, $user ) {
        if ( empty( $_POST['city'] ) ) {
            $errors->add( 'city_empty', __( 'City field cannot be left empty.' ) );
        }
    }, 10, 3 );

Let’s see a code example of apply_filters_ref_array().

让我们看一下apply_filters_ref_array()的代码示例。

The code below hooks into the bp_activity_permalink_redirect_url filter in bbPress to modify the intended redirect URL to http://website.com/custom-page/ before the redirect occurs for a single activity item.

下面的代码连接到bbPress的bp_activity_permalink_redirect_url过滤器中,以在将单个活动项目重定向之前,将预期的重定向URL修改为http://website.com/custom-page/

add_filter( 'bp_activity_permalink_redirect_url', function ( $redirect, $activity ) {
        $redirect = 'http://website.com/custom-page/';

        return $redirect;

    }, 10, 2 );

何时使用do_action_ref_array()apply_filters_ref_array() (When to Use do_action_ref_array() and apply_filters_ref_array())

In making your plugin or theme extensible by other developers, do_action_ref_array() and apply_filters_ref_array() are preferable to do_action() and apply_filters() when there are many additional variables or values to be passed to functions that hook into an action and filter are many.

在其他开发人员对你的插件或主题可扩展的, do_action_ref_array()apply_filters_ref_array()是优选do_action()apply_filters()时有许多另外的变量或值被传递到函数钩入actionfilter有许多。

Take for instance, you’re developing a user registration plugin, and you defined an action to fire after registration is complete with the registered user’s username, email address, first name, last name, address, city, state and country available to functions that hook to it. Here is how the code might look when you use do_action()

例如,您正在开发一个用户注册插件,并定义了一个注册完成后要执行的操作,注册完成时注册用户的用户名,电子邮件地址,名字,姓氏,地址,城市,州和国家/地区可以使用的功能钩上它。 这是使用do_action()时代码的外观

do_action('after_user_registration_completed', $username, $email, $firstname, $lastname, $address, $city, $state, $country);

Notice how the list of arguments makes the line of code long and ugly. Now compare the above with that of do_action_ref_array() below.

注意参数列表如何使代码行冗长而丑陋。 现在将上面的内容与下面的do_action_ref_array()进行比较。

do_action_ref_array(
    'after_user_registration_completed',
    array(
        $username,
        $email,
        $firstname,
        $lastname,
        $address,
        $city,
        $state,
        $country
    )
);

将类方法挂接到动作和过滤器 (Hooking Class Methods to Actions and Filters)

The code examples we’ve been examining are about hooking named and anonymous functions to action and filter hooks.

我们一直在研究的代码示例是关于将命名函数和匿名函数挂钩到actionfilter挂钩的。

So let’s see how to call or include hooks via add_action() and add_filter() within a class for processing during WordPress execution and also how class methods (static and non-static) can be hooked to actions and filters.

因此,让我们看看如何在类中通过add_action()add_filter()调用或包含钩子,以便在WordPress执行期间进行处理,以及如何将类方法(静态和非静态)钩接到actionsfilters

Most WordPress developers include all add_action() and add_filter() function calls in their class constructor which is then executed on instantiation like so:

大多数WordPress开发人员在其类构造函数中包含所有add_action()add_filter()函数调用,然后在实例化时执行,如下所示:

class DemoPlugin {
    public function __construct() {
        add_action( 'wp_head', array( $this, 'google_site_verification' ) );

        add_filter( 'the_content', array( $this, 'we_love_sitepoint' ) );
    }


    /**
     * Include Google site verification meta tag to WordPress header.
     */
    public function google_site_verification() {
        echo '<meta name="google-site-verification" content="ytl89rlFsAzH7dWLs_U2mdlivbrr_jgV4Gq7wClHDUJ8" />';
    }


    /**
     * Append and prepend the text "We love SitePoint" to every post content.
     *
     * @param string $content
     *
     * @return string
     */
    public function we_love_sitepoint( $content ) {
        $text    = sprintf( '<div class="notice alert">%s</div>', __( 'We love SitePoint', 'sp' ) );
        $content = $text . $content . $text;

        return $content;
    }
}


new DemoPlugin();

From the code snippet above, you will discover that there is a difference in the way a function and class method is hooked to an action or filter in that, for a class method, the second argument of add_action() and add_filter() is an array of $this (a reference to the current object) and the method name.

从上面的代码片段中,您会发现函数和类方法与actionfilter连接方式有所不同,对于类方法, add_action()add_filter()的第二个参数是$this数组(对当前对象的引用)和方法名称。

For a static method, the class name is used instead of $this.

对于静态方法,使用类名代替$this

class DemoPlugin {
    public function __construct() {
        add_action( 'wp_head', array( 'DemoPlugin', 'google_site_verification' ) );
    }


    /**
     * Include Google site verification meta tag to WordPress header.
     */
    public static function google_site_verification() {
        echo '<meta name="google-site-verification" content="ytl89rlFsAzH7dWLs_U2mdlivbrr_jgV4Gq7wClHDUJ8" />';
    }
}

new DemoPlugin();

The above approach of including the class name for every static method you want to hook to a filter or action violates the don’t repeat yourself (DRY) principle and thus will make refactoring hard.

上面为要挂接到过滤器或操作的每个静态方法包括类名的方法违反了“ 不要重复自己”(DRY)原则,因此将使重构变得困难。

Instead, use the constant __CLASS__ which returns the class name it was declared in.

而是使用常量__CLASS__ ,该常量返回在其中声明的类名称。

class DemoPlugin {
    public function __construct() {
        add_action( 'wp_head', array( __CLASS__, 'google_site_verification' ) );
    }

    // ...
}

new DemoPlugin();

Although I strongly discourage this, here is another way of including a static method to a hook.

尽管我强烈建议不要这样做,但这是将静态方法包括在钩子中的另一种方法。

class DemoPlugin {
    public function __construct() {
        add_action( 'wp_head', 'DemoPlugin::google_site_verification' );
    }

    // ...
}

new DemoPlugin();

Rather than include all add_action() and add_filter() function calls in a class constructor, I have seen some developers create a static class method which when called, initializes/executes the static methods hooked to an action or filter.

我看到有些开发人员没有在类构造函数中包含所有add_action()add_filter()函数调用,而是创建了一个静态类方法,该方法在被调用时初始化/执行挂接到动作或过滤器的静态方法。

class DemoPlugin {
    public static function init() {
        add_action( 'wp_head', array( __CLASS__, 'google_site_verification' ) );
        add_filter( 'the_content', array( __CLASS__, 'we_love_sitepoint' ) );
    }

    // ...
}


DemoPlugin::init();

In this approach, all methods to be hooked to actions and filters must be static because $this is not accessible in static context.

在这种方法中,所有挂接到actionsfilters必须是静态的,因为$this在静态上下文中不可访问。

摘要 (Summary)

In this second part of our series on WordPress hooks, we learned an alternative way of triggering action and filter events, when to use them, and finally, how to hook static and non-static class methods to actions and filters.

在有关WordPress钩子的系列的第二部分中,我们学习了触发动作和过滤器事件的另一种方法,何时使用它们,以及最后如何将静态和非静态类方法钩接到动作和过滤器。

In the concluding part, we’ll examine how to hook methods of an instantiated class (object) to an action and filter, how to integrate a namespaced class method to a hook and the caveats of using namespaces in the WordPress hook system.

在最后一部分,我们将研究如何将实例化类(对象)的方法挂钩到动作和过滤器,如何将命名空间的类方法集成到挂钩,以及在WordPress挂钩系统中使用命名空间的注意事项。

Happy coding!

祝您编码愉快!

翻译自: https://www.sitepoint.com/triggering-events-in-wordpress/

参与评论 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值