wordpress插件开发
Are you looking for an introduction to WordPress plugin development that will discuss all of the important steps and hold your hand along the way? If so, you’re in luck. This tutorial will outline the basics of what you need to know about designing your own plugins and some pointers on best practices.
您是否正在寻找WordPress插件开发的介绍,该讨论将讨论所有重要步骤并一路过关斩将? 如果是这样,那么您很幸运。 本教程将概述您在设计自己的插件时需要了解的基础知识,以及一些有关最佳做法的指针。
Plugins are one of WordPress’ most powerful assets. In essence, plugins are modules you activate on your website to provide a series of features or elements.
插件是WordPress最强大的资产之一。 本质上,插件是您在网站上激活以提供一系列功能或元素的模块。
The functionality you can add to your website depends on what each specific plugin has been created to do. There are a wide selection of plugins, ranging from simple plugins (such as ones that add styling or small theme changes) all the way to extensive plugins (that provide significant changes such as eCommerce integrations or third party connections).
您可以添加到网站的功能取决于每个特定插件的创建方式。 插件的选择范围很广,从简单的插件(例如添加样式或小的主题更改的插件)一直到扩展的插件(提供重大更改,例如电子商务集成或第三方连接)。
Plugins are different from your theme and work independently, using hooks, filters, shortcode, widgets and custom code to perform their functionality.
插件与您的主题不同,并且可以独立使用钩子,过滤器,短代码,小部件和自定义代码来执行其功能。
Plugins are great, they provide both developers and admins with a way to extend and re-use functionality. While they are a great tool they do still have both their strengths and weaknesses.
插件很棒,它们为开发人员和管理员提供了一种扩展和重用功能的方法。 尽管它们是一个很好的工具,但是它们仍然具有优点和缺点。
Let’s take a moment to talk about some key aspects of plugin development.
让我们花一点时间讨论插件开发的一些关键方面。
You might be familiar with these areas if you have worked on WordPress themes, however, a solid understanding of how these concepts work will help you build easy to use and maintainable functionality.
如果您曾经处理过WordPress主题,那么您可能熟悉这些领域,但是,对这些概念的工作原理有深入的了解将有助于您构建易于使用和可维护的功能。
An action hook is an activity that is performed by WordPress at a specific time. When this action is triggered it will find all functions that have been attached to this action and execute them in the correct order.
action挂钩是WordPress在特定时间执行的活动。 触发此操作后,它将找到该操作已附加的所有功能,并以正确的顺序执行它们。
WordPress has dozens of actions defined throughout its core functionality, each action consisting of a unique name. For example, when WordPress is saving a post (such as a post, page or other content type) it will call the action save_postwhich will look for any functions attached to this action.
WordPress在其整个核心功能中定义了许多动作,每个动作都由一个唯一的名称组成。 例如,当WordPress保存帖子(例如帖子,页面或其他内容类型)时,它将调用操作save_post ,该操作将查找与此操作相关的所有功能。
All actions are defined using the do_action() function. This function takes in the following parameters
所有动作均使用do_action()函数定义。 该函数采用以下参数
$tag (required)
$tag (必填)
$args (optional one or more variables)
$args (可选的一个或多个变量)
Overall, each action will have its name (its tag) and also an optional number of additional useful variables (there could be multiple or zero additional variables)
总的来说,每个动作都会有其名称(其标记)以及可选数量的其他有用变量(可能有多个或零个附加变量)
Let’s consider the save_post action hook. This action takes in four values. The first value is the name of the action, while the other three are additional variables that can be accessed (containing the id of the post, the post object itself and also if the posts exists and is being updated)
让我们考虑一下save_post操作钩子。 此操作采用四个值。 第一个值是操作的名称,而其他三个是可以访问的其他变量(包含帖子的ID,帖子对象本身,以及帖子是否存在以及是否正在更新)
//the save_post action hook do_action(`save_post`, $post_ID, $post, $update);You can hook onto this action so that when a post is saved you can do something else, such as send and email or update the database.
您可以使用此操作,以便在保存帖子时可以执行其他操作,例如发送和发送电子邮件或更新数据库。
While WordPress comes with plenty of actions you can define your own. Creating your own actions will give you an easy way to call your functionality at set points throughout your theme or plugin.
尽管WordPress附带了很多动作,但是您可以定义自己的动作。 创建自己的动作将为您提供一种简便的方法,可以在整个主题或插件的设定点调用功能。
Let’s use the do_action function to create our new action. We will be creating an action that will be called straight after the title on single pages.
让我们使用do_action函数创建我们的新动作。 我们将创建一个动作,该动作将在单pages title之后立即被调用。
//create a new action to be used after our page title do_action('page_subtitle', $post);When a single page is displayed it will show the title as normal and then afterwards it will hit our page_subtitle action. WordPress will check for any functions hooked to this action and execute them (it will pass in the global $post variable so the function knows what page it is supposed to show the subtitle for).
当显示单个page ,它将显示正常的标题,然后单击我们的page_subtitle操作。 WordPress将检查与该操作相关的任何函数并执行它们(它将传入全局$post变量,以便该函数知道应该显示其字幕的页面)。
To call a specific function when an action is taking place, you need to use add_action() to attach your function. add_action takes then following parameters.
要在发生动作时调用特定的函数,您需要使用add_action()附加函数。 add_action然后采用以下参数。
$hook (required)
$hook (必填)
$function_to_add (required)
$function_to_add (必需)
$priority (optional)
$priority (可选)
$accepted_args(optional, but required when the action has more than one passed variables)
$accepted_args (可选,但在操作具有多个传递的变量时是必需的)
You can call the add_action function by supplying the mandatory values of the hook name and the function to call. This is the easiest way to call your actions.
您可以通过提供钩子名称和要调用的函数的必需值来调用add_action函数。 这是调用操作的最简单方法。
//when 'save_post' is triggered, call our saving function add_action('save_post','save_my_custom_post'); //defines our function that will handle our saving function save_my_custom_post($post_id){ //you will do your saving here }As you can see, when the save_post action occurs we attach our save_my_custom_post function to it, giving us access to do something after we save.
如您所见,当save_post操作发生时,我们将save_my_custom_post函数附加到该函数,从而使我们可以在保存后执行某些操作。
Sometimes using the mandatory values wont be enough. You may have to manually set the $priority and $accepted_args values to make your action work.
有时使用强制性值是不够的。 您可能必须手动设置$priority和$accepted_args值才能使操作起作用。
The priority of the action determines the order in which functions will be executed. By default actions will use the value of 10 for its priority. You can set this value either higher or lower to make your function execute earlier or later. This is useful when your theme or plugins are also using the same action hook (so you can specify when your function should run).
动作的priority决定了功能执行的顺序。 默认情况下,操作将使用10作为其优先级。 您可以将此值设置得更高或更低,以使您的函数更早或更晚地执行。 当您的主题或插件也使用相同的动作挂钩时,此功能很有用(因此您可以指定何时运行函数)。
The accepted_args refer to how many variables are being passed in the add_action call. The default number of arguments that an action accepts will be one. However, if your action takes in multiple variables you have to tell WordPress how many it is taking. Let’s look at the save_post action.
accepted_args指的是在add_action调用中传递了多少个变量。 动作接受的默认参数个数为1。 但是,如果您的操作包含多个变量,则必须告诉WordPress正在执行多少操作。 让我们看一下save_post动作。
//the save post action, defined in WordPress do_action( 'save_post', $post_ID, $post, $update ); //add our function onto the 'save_post' hook, supplying priority and args add_action('save_post','save_my_page_extended,10,3); //function executed on save (we want all three variables) function save_my_page_extended($post_ID, $post, $update){ //access all of our variables to do some work }The save_post action has multiple variables that can be passed to it, as such we have to set its priority and also the number of variables it will be passing. Once we have told WordPress we will be accepting multiple variables, we can add these into our function and we will be able to access them.
save_post操作具有多个可以传递给它的变量,因此我们必须设置其优先级以及传递的变量数量。 告诉WordPress之后,我们将接受多个变量,我们可以将它们添加到函数中,然后就可以访问它们。
Overall, you will use the do_action function inside of your theme or plugin to execute code at a set location (setting the values that will be available to any hooked function). You will then use the add_action function to hook on your specific function. You can call your action with just the bare minimum (the name of the action and the function you want to call), or you can also supply the priority and number of variables that will be passed,
总体而言,您将在主题或插件内部使用do_action函数在设置的位置执行代码(设置将对任何挂钩函数可用的值)。 然后,您将使用add_action函数挂接您的特定函数。 您可以只调用最小的操作(操作的名称和要调用的函数),也可以提供将要传递的变量的优先级和数量,
A WordPress filter is a hook that accepts a variable (or series of variables) and returns them back after they have been modified. These filters are often used so that you have a way to manipulate default information.
WordPress filter是一个接受变量(或一系列变量)并在修改后返回它们的钩子。 经常使用这些过滤器,以便您可以操纵默认信息。
WordPress comes bundled with dozens of these filters and they are created using the apply_filters() function. This function takes in the following arguments
WordPress捆绑了许多此类过滤器,它们是使用apply_filters()函数创建的。 此函数接受以下参数
$tag (required)
$tag (必填)
$value (required)
$value (必填)
$var (optional)
$var (可选)
The $tag variable is the name of the filter. The $value is the variable or value that will be filtered. The $var variable is optional but allows you to pass extra values into your function.
$tag变量是过滤器的名称。 $value是将被过滤的变量或值。 $var变量是可选的,但允许您将其他值传递到函数中。
Plugins and themes often create these filters so that you can change elements without having to modify the source itself (making them extensible). These filters are often defined inside functions.
插件和主题通常会创建这些过滤器,以便您可以更改元素而不必修改源本身(使它们可扩展)。 这些过滤器通常在函数内部定义。
The get_the_excerpt filter is a filter that you can use inside the posts loop to access the excerpt.
get_the_excerpt过滤器是一个过滤器,您可以在posts循环内使用该过滤器来访问摘录。
This filter is defined as part of WordPress’s core and only defines the name of the filter and the function to call, it doesn’t define any optional arguments.
此过滤器被定义为WordPress核心的一部分,仅定义了过滤器的名称和要调用的函数,并未定义任何可选参数。
//get the except for a post, as defined in /wp-includes/post-template.php echo apply_filters( 'the_excerpt', get_the_excerpt() );You could attach your own function to the the_excerpt filter and then manipulate the excerpt before you return it (for example, you could wrap it inside a container, change its content or trim its length).
您可以将自己的函数附加到the_excerpt筛选器上,然后在返回the_excerpt之前对其进行操作(例如,可以将其包装在容器中,更改其内容或修剪其长度)。
Let’s look at an example. If we are creating an array of names in a plugin we can make it filterable by using the apply_filters hook to tell WordPress that these values can be changed by any function that hooks onto them.
让我们来看一个例子。 如果我们要在插件中创建名称数组,则可以通过使用apply_filters挂钩告诉WordPress这些值可以通过任何挂钩到它们的函数来更改,从而使其可过滤。
//make our name value array filterable $name_values = apply_filters('filter_name_array_values', array('Joanna','Peter') );Creating a filter like this will let other developers (or yourself) change these values in a dynamic way. Generally, if you are inside a function or doing some sort of functionality it is good practice to offer filters to make your elements extensible.
创建这样的过滤器将使其他开发人员(或您自己)以动态方式更改这些值。 通常,如果您在某个函数内部或正在执行某种功能,则最好提供过滤器以使您的元素可扩展。
When you want to execute your filter you will need to use the add_filter() function. This function takes the following values
当您要执行过滤器时,您将需要使用add_filter()函数。 此函数采用以下值
$tag (required)
$tag (必填)
$function_to_add (required)
$function_to_add (必需)
$priority (optional)
$priority (可选)
$accepted_args (optional but mandatory if we have multiple passed arguments)
$accepted_args (可选,但如果我们有多个传递的参数则为必需)
The add_filter function works in a similar way to add_action. You define the name of the filter you want to call, along with the function that will be called and you’re good to go. Let’s look at how we can use this to filter the list of names we created in our previous example.
add_filter函数的工作方式与add_action相似。 您定义了要调用的过滤器的名称,以及将要调用的函数,这很好。 让我们看一下如何使用它来过滤在上一个示例中创建的名称列表。
//Change the saved name values by filtering them function add_new_names($names){ $names[] = 'Simon'; return $names; } add_filter('filter_name_array_values','add_new_names');As you can see we are attaching our add_new_names function onto our filter_name_array_values filter and taking in a single variable of $names. When we defined our filter before with apply_filters we set the default values to be an array with the values of Joanna and Peter.
如您所见,我们将add_new_names函数附加到filter_name_array_values过滤器上,并接受一个$names变量。 当我们之前使用apply_filters定义过滤器时,我们将默认值设置为具有Joanna和Peter值的数组。
Our function here will take the existing values (which we have called $names here for simplicity) and added a new value onto the end of it called Simon.
我们这里的函数将采用现有的值(为简单起见,在这里我们将其称为$names ),并在其末尾添加一个新值,即Simon。
At the very end we return the values. Returning the values is very very important, if you don’t you will break everything. The reason the values must be returned is because any additional function also attached to that filter will receive these values. If you don’t return them they will have nothing to use.
最后,我们返回值。 返回值非常重要,如果不这样做,则会破坏一切 。 必须返回值的原因是因为任何附加到该过滤器的附加功能都将接收这些值。 如果您不退货,它们将一无所有。
You will use the apply_filters function to create your filters inside your theme or plugin (supplying the values you wish to filter). You will then use the add_filter function to hook your specific function onto this filter, allowing you to manipulate the filtered variable and return it).
您将使用apply_filters函数在主题或插件内创建过滤器(提供要过滤的值)。 然后,您将使用add_filter函数将特定函数挂接到此过滤器上,从而允许您操作过滤后的变量并将其返回)。
For a more comprehensive article on shortcodes you can read or view the shortcode API on the WordPress Codex or read my previous article on Custom WordPress Shortcodes. The following will be a brief summary to get you up and running with shortcodes.
要获得有关简码的更全面的文章,您可以阅读或查看WordPress Codex上的简码API,或者阅读我以前关于“ 自定义WordPress简码”的文章。 以下是简短的摘要,可帮助您入门并使用短代码。
Since your plugin generally won’t have access to your theme files, you need a way to display your custom functionality to the end user while making it easy to customize by your site admin.
由于您的插件通常无法访问您的主题文件,因此您需要一种向最终用户显示自定义功能的方法,同时使您的站点管理员可以轻松自定义功能。
Shortcodes are perfect way to do this as they allow developers to create complex functionality that can be modified with simple values and attributes. These shortcodes are added to the visual editor (or other locations) and when viewed by your users they execute your code.
短代码是执行此操作的理想方法,因为它们允许开发人员创建可以用简单值和属性修改的复杂功能。 这些短代码将添加到可视化编辑器(或其他位置)中,并在用户查看时执行您的代码。
A shortcode in the editor:
编辑器中的简码:
A shortcode when processed and displayed on the front end:
处理并显示在前端的简码:
You will need to create your shortcode using the add_shortcode() function. This function will take in the first variable as the name of your shortcode and the second being the output_function.
您将需要使用add_shortcode()函数创建您的简码。 该函数将第一个变量作为您的短代码name ,第二个变量作为output_function 。
The output_function will itself take three values; attributes, content and name. Inside of this function you will build your shortcode and return it for display.
output_function本身将采用三个值; attributes , content和name 。 在此函数内,您将构建您的简码并将其返回以显示。
The parameters of the function will be looked at in further detail in our example, right now it’s fine to just ignore them.
在我们的示例中将更详细地查看函数的参数,现在可以忽略它们。
Let’s look at a simple example:
让我们看一个简单的例子:
//Add our shortcode add_shortcode('test_shortcode','my_shortcode_output'); //perform the shortcode output function my_shortcode_output($atts, $content = '', $tag){ $html = ''; $html .= '<p>Hello World</p>'; return $html; }Now when we add the shortcode [test_shortcode] to the editor it will run our function and convert the results to <p>Hello World</p>
现在,当我们将简码[test_shortcode]添加到编辑器中时,它将运行我们的函数并将结果转换为<p>Hello World</p>
If you are looking at learning more about widgets you should start with the WordPress Widget API codex page. This page outlines the majority of what you need plus it provides a documented working example.
如果您想了解有关小部件的更多信息,则应从WordPress Widget API Codex页面开始 。 该页面概述了您所需要的大部分内容,并提供了一个记录在案的工作示例。
Widgets are important because they give you another means of executing your plugins code while providing an easy to use interface.
小部件很重要,因为它们为您提供了另一种执行插件代码的方法,同时提供了易于使用的界面。
A sample shortcode with configuration options.
带有配置选项的示例短代码。
Since most themes will support one or more sidebars; adding your own widgets will give you quick access to display your information inside the theme.
由于大多数主题将支持一个或多个侧边栏; 添加您自己的窗口小部件将使您可以快速访问以在主题内显示信息。
Widgets are more complex than shortcodes but follow the same principals – defining some options for its output and then displaying it on the front-end.
小部件比短代码更复杂,但是遵循相同的原理-为其输出定义一些选项,然后将其显示在前端。
To create a widget you need to extend the WP_Widget class. WordPress has created an object orientated approach to widgets and they exists as a class; this class needs to be extended to provide your functionality.
要创建小部件,您需要扩展WP_Widget类。 WordPress创建了一种面向对象的小部件方法,它们作为类存在。 此类需要扩展以提供您的功能。
Let’s look at a basic widget example:
让我们看一个基本的小部件示例:
//class for our widget class my_widget extends WP_widget{ //constructor (sets basic elements for the widget) public function __construct(){ parent::__construct( 'my_widget', // Base ID 'My Widget', // Name array( 'description' => 'An awesome widget') // Args ); add_action('widgets_init',array($this,'register_widget')); } //handles front end display public function widget($args,$instance ){ echo $args['before_widget']; echo $instance['title']; echo $args['after_widget']; } //handles back end widget display public function form($instance){ $title = (isset($instance['title']) ? $instance['title'] : ''); echo '<input type="text" id="' . $this->get_field_id('title') . '" name="' . $this->get_field_name('title') . '" value="' . $title . '"/>'; } //handles saving public function save($new_instance, $old_instance){ $instance = array(); $title = $new_instance['title']; return $instance; } //registers the widget with WordPress public function register_widget(){ register_widget('my_widget'); } } $my_widget = new my_widget;This will produce a basic widget in which you can save a text value and display it to the front end, as you can see the output is pretty boring.
这将产生一个基本的小部件,您可以在其中保存文本值并将其显示在前端,因为您可以看到输出非常无聊。
In the upcoming real world example we will look into widgets in more depth.
在即将到来的真实示例中,我们将更深入地研究小部件。
Object Orientated Design (OOD) is a different development technique in which you build your functionality around the concept of classes.
面向对象设计(OOD)是一种不同的开发技术,您可以围绕classes的概念来构建功能。
Classes are a way to store related functions and values inside of a single entity, giving you a single location for your development. The overall purpose of object orientated design is create an object that performs your functionality.
类是在单个实体内部存储相关功能和值的一种方法,为您的开发提供了单个位置。 面向对象设计的总体目的是创建一个执行功能的object 。
Plugins are a perfect candidate for object orientated design as they are separate modules created to perform a task on your website. Your plugin will generally contain its own CSS and JavaScript files along with potentially images and additional PHP files, so developing using object orientated design will make your development easier.
插件是面向对象设计的理想选择,因为它们是为在您的网站上执行任务而创建的独立模块。 您的插件通常将包含其自己CSS和JavaScript文件以及可能的图像和其他PHP文件,因此使用面向对象的设计进行开发将使您的开发更加容易。
Our upcoming real world example will be entirely object orientated. If you are interested in reading more you could have a read of my article Object Orientated Development with WordPress.
我们即将到来的现实世界示例将完全面向对象。 如果您有兴趣阅读更多内容,可以阅读我的文章WordPress面向对象开发 。
This article has introduced you to many of the core concepts needed for WordPress plugin development. In the next article, we’ll take a detailed look at the code of a real world example.
本文向您介绍了WordPress插件开发所需的许多核心概念。 在下一篇文章中,我们将详细介绍真实示例的代码 。
翻译自: https://www.sitepoint.com/an-introduction-to-wordpress-plugin-development/
wordpress插件开发
相关资源:wordpress 插件开发cookbook原书高清pdf及随书代码