热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

InthefirstpartofthisseriesontheWordPresshooksystem,welearnedabouttheWordPresshooksystemand

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 '';
}
/**
* 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( '

%s
', __( '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 '';
}
}
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/




推荐阅读
  • HDFS2.x新特性
    一、集群间数据拷贝scp实现两个远程主机之间的文件复制scp-rhello.txtroothadoop103:useratguiguhello.txt推pushscp-rr ... [详细]
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • r2dbc配置多数据源
    R2dbc配置多数据源问题根据官网配置r2dbc连接mysql多数据源所遇到的问题pom配置可以参考官网,不过我这样配置会报错我并没有这样配置将以下内容添加到pom.xml文件d ... [详细]
  • PDO MySQL
    PDOMySQL如果文章有成千上万篇,该怎样保存?数据保存有多种方式,比如单机文件、单机数据库(SQLite)、网络数据库(MySQL、MariaDB)等等。根据项目来选择,做We ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • 本文介绍了数据库的存储结构及其重要性,强调了关系数据库范例中将逻辑存储与物理存储分开的必要性。通过逻辑结构和物理结构的分离,可以实现对物理存储的重新组织和数据库的迁移,而应用程序不会察觉到任何更改。文章还展示了Oracle数据库的逻辑结构和物理结构,并介绍了表空间的概念和作用。 ... [详细]
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • 本文介绍了Perl的测试框架Test::Base,它是一个数据驱动的测试框架,可以自动进行单元测试,省去手工编写测试程序的麻烦。与Test::More完全兼容,使用方法简单。以plural函数为例,展示了Test::Base的使用方法。 ... [详细]
  • 本文介绍了高校天文共享平台的开发过程中的思考和规划。该平台旨在为高校学生提供天象预报、科普知识、观测活动、图片分享等功能。文章分析了项目的技术栈选择、网站前端布局、业务流程、数据库结构等方面,并总结了项目存在的问题,如前后端未分离、代码混乱等。作者表示希望通过记录和规划,能够理清思路,进一步完善该平台。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 本文讨论了在数据库打开和关闭状态下,重新命名或移动数据文件和日志文件的情况。针对性能和维护原因,需要将数据库文件移动到不同的磁盘上或重新分配到新的磁盘上的情况,以及在操作系统级别移动或重命名数据文件但未在数据库层进行重命名导致报错的情况。通过三个方面进行讨论。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • CentOS 6.5安装VMware Tools及共享文件夹显示问题解决方法
    本文介绍了在CentOS 6.5上安装VMware Tools及解决共享文件夹显示问题的方法。包括清空CD/DVD使用的ISO镜像文件、创建挂载目录、改变光驱设备的读写权限等步骤。最后给出了拷贝解压VMware Tools的操作。 ... [详细]
  • web.py开发web 第八章 Formalchemy 服务端验证方法
    本文介绍了在web.py开发中使用Formalchemy进行服务端表单数据验证的方法。以User表单为例,详细说明了对各字段的验证要求,包括必填、长度限制、唯一性等。同时介绍了如何自定义验证方法来实现验证唯一性和两个密码是否相等的功能。该文提供了相关代码示例。 ... [详细]
  • 本文讨论了如何在codeigniter中识别来自angularjs的请求,并提供了两种方法的代码示例。作者尝试了$this->input->is_ajax_request()和自定义函数is_ajax(),但都没有成功。最后,作者展示了一个ajax请求的示例代码。 ... [详细]
author-avatar
luomo
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有