wordpress插件开发
If you’ve ever used WordPress to build a site quickly, chances are you’ve used one of the many plugins that are offered to extend the functionality of this popular blogging software. Plugins are one of the many things that make WordPress so attractive. If you need an image gallery or a contact form, there’s probably a plugin already available that you can download and use. There are times, however, when you can’t quite find what you need from existing plugins. This article will show you how to create your own WordPress plugins by walking you through an example to display some text using a widget in a the sidebar.
如果您曾经使用WordPress来快速构建网站,那么您很有可能使用了众多可扩展此流行博客软件功能的插件之一。 插件是使WordPress如此吸引人的众多因素之一。 如果您需要图片库或联系表,则可能已经有一个插件可以下载和使用。 但是,有时您可能无法从现有插件中找到所需的东西。 本文将通过逐步介绍一个示例以使用侧边栏中的小部件显示一些文本,向您展示如何创建自己的WordPress插件。
Plugins are detected automatically from the wp-content/plugins directory within your WordPress installation directory. When creating a new plugin, you should create a new subdirectory there. The name of the subdirectory can be anything you want; a sensible option would be to call it the name of your plugin. Try to avoid generic names such as “textwidget” or “shoppingcart” as this may have already been used with another plugin and will cause problems should you wish to distribute it to other users of WordPress. For this example, create a subdirectory named phpmaster_examplewidget.
插件会自动从WordPress安装目录中的wp-content/plugins目录中检测到。 创建新插件时,应在此处创建一个新的子目录。 子目录的名称可以是您想要的任何名称。 一个明智的选择是将其称为插件的名称。 尽量避免使用诸如“ textwidget”或“ shoppingcart”之类的通用名称,因为该名称可能已与另一个插件一起使用,如果您希望将其分发给其他WordPress用户,则会引起问题。 对于此示例,创建一个名为phpmaster_examplewidget的子目录。
WordPress detects that a plugin is available from a descriptor placed in the comments of a PHP file. The descriptor must provide the basic information about what the plugin does, who created it, and its license information. This is what WordPress uses to identify that a plugin is present and ready to be activated. This example plugin will contain the definition at the top a file placed in your newly created phpmaster_examplewidget directory. The name of the file is also arbitrary but it’s advisable to provide a meaning name. This example will call the file widget_init.php.
WordPress从放置在PHP文件注释中的描述符中检测到有可用的插件。 描述符必须提供有关插件功能,创建者及其许可证信息的基本信息。 这就是WordPress用于识别存在插件并准备激活的插件。 该示例插件将在顶部的定义中包含一个文件,该文件位于您新创建的phpmaster_examplewidget目录中。 文件名也可以是任意的,但建议提供含义名称。 此示例将调用文件widget_init.php 。
<?php /* Plugin Name: Simple Text Plugin Plugin URI: http://www.example.com/textwidget Description: An example plugin to demonstrate the basics of putting together a plugin in WordPress Version: 0.1 Author: Tim Smith Author URI: http://www.example.com License: GPL2 Copyright 2011 Tim Smith This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */This is the required structure for any plugin you’ll create for WordPress. Now when you log in and look at the plugin administration screen in WordPress you’ll see the new plugin is ready for activation.
这是您将为WordPress创建的任何插件的必需结构。 现在,当您登录并查看WordPress中的插件管理屏幕时,您将看到新的插件已准备就绪,可以激活。
You can see all of the information you entered in the comments section describing the plugin is displayed here. You can activate it now if you wish, but you still need to add some functionality before it does anything.
您可以在此处看到在注释部分中输入的描述该插件的所有信息,这些信息将在此处显示。 您可以根据需要立即激活它,但是在执行任何操作之前,您仍然需要添加一些功能。
The file that has this definition is now considered to be the starting point for any code associated with the plugin. The code that appears after the definition comments will be executed giving you the opportunity to initialize the plugin and its features.
现在,具有此定义的文件被视为与插件关联的任何代码的起点。 将执行定义注释后显示的代码,使您有机会初始化插件及其功能。
WordPress provides a class which you can extend named WP_Widget. When you extend it, your own widget will be available to any sidebar that your theme offers. WordPress ships with a number of default widgets such as “Recent Posts” and “Archives” which extend WP_Widget.
WordPress提供了一个可以扩展的类WP_Widget 。 扩展它时,您自己的窗口小部件将可用于主题提供的任何侧边栏。 WordPress随附了许多默认小部件,例如扩展WP_Widget “最新帖子”和“存档”。
The WP_Widget class provides four methods which should be overridden:
WP_Widget类提供了四个应重写的方法:
__construct() – call the parent constructor and initialize any class variables
__construct() –调用父构造函数并初始化任何类变量
form() – display a form for the widget in the admin view to customize the widget’s properties
form() –在管理视图中显示窗口小部件的表单以自定义窗口小部件的属性
update() – update the widget’s properties specified in the form in the admin view
update() –更新在管理员视图中的表单中指定的小部件的属性
widget() – display the widget on the blog
widget() –在博客上显示小部件
The constructor is like any other constructor you’ve probably written. The important thing to remember here is to call the parent constructor which can take three arguments: an identifier for the widget, the friendly name of the widget (this will appear as the title of the widget in the admin widget screen), and an array detailing the properties of the widget (which only needs a “description” value).
该构造函数与您可能编写的任何其他构造函数一样。 这里要记住的重要一点是调用父构造函数,它可以接受三个参数:小部件的标识符,小部件的友好名称(将在管理小部件屏幕中显示为小部件的标题)和数组详细说明窗口小部件的属性(仅需要“描述”值)。
<?php class TextWidget extends WP_Widget { public function __construct() { parent::__construct("text_widget", "Simple Text Widget", array("description" => "A simple widget to show how WP Plugins work")); } }With the basic widget structure in place, you’ll want to register the widget and make sure this is done at a time when all the other widgets are being initialized. Registering a widget is done through the register_widget() function which takes a single argument, the name of the class which extends WP_Widget. This call to register the widget must be called at an appropriate time, so the particular WordPress hook you’ll want to use is called “widgets_init”. To associate registering the widget with the hook, you use add_action() which takes the name of the hook as the first argument and a function to execute as the second. (The second argument can either be the string name of a function or closure.) This code should go directly under the descriptor of the plugin that was created in widget_init.php.
使用基本的窗口小部件结构后,您将需要注册该窗口小部件并确保在初始化所有其他窗口小部件时完成此操作。 小部件的register_widget()是通过register_widget()函数完成的,该函数接受一个参数,即扩展WP_Widget的类的名称。 必须在适当的时间调用此注册小部件的调用,因此您要使用的特定WordPress钩子称为“ widgets_init”。 要将注册小部件与挂钩相关联,请使用add_action() ,它将挂钩的名称作为第一个参数,并将要执行的函数作为第二个参数。 (第二个参数可以是函数或闭包的字符串名称。)此代码应直接放在widget_init.php中创建的插件的描述符下。
<?php add_action("widgets_init", function () { register_widget("TextWidget"); }); ?>Now that it has been registered and initialized, you’ll be able to see your widget available for use.
现在,它已经被注册和初始化,您将能够看到您的小部件可用。
The example widget here should let you enter a title and some text to be displayed when viewed on the blog, so in order to be able to amend these two aspects of the widget you need to create a form to prompt for these values. The form() method is used in the widget administration screen to display fields which you can later use to alter the functionality of the widget on the site itself. The method takes one argument, an $instance array of variables associated with the widget. When the form is submitted, the widget will call the update() method which allows you to update the fields in $instance with new values. Later, widget() will be called and will make use of $instance to display the values.
此处的示例窗口小部件应允许您输入标题和在博客上查看时要显示的一些文本,因此,为了能够修改窗口小部件的这两个方面,您需要创建一个表单以提示输入这些值。 窗口小部件管理屏幕中使用form()方法显示字段,以后您可以使用这些字段来更改站点本身上的窗口小部件的功能。 该方法采用一个参数,即与微件关联的变量的$instance数组。 提交表单后,小部件将调用update()方法,该方法允许您使用新值更新$instance的字段。 稍后,将调用widget()并将利用$instance显示值。
<?php public function form($instance) { $title = ""; $text = ""; // if instance is defined, populate the fields if (!empty($instance)) { $title = $instance["title"]; $text = $instance["text"]; } $tableId = $this->get_field_id("title"); $tableName = $this->get_field_name("title"); echo '<label for="' . $tableId . '">Title</label><br>'; echo '<input id="' . $tableId . '" type="text" name="' . $tableName . '" value="' . $title . '"><br>'; $textId = $this->get_field_id("text"); $textName = $this->get_field_name("text"); echo '<label for="' . $textId . '">Text</label><br>'; echo '<textarea id="' . $textId . '" name="' . $textName . '">' . $text . '</textarea>'; }You use WP_Widget‘s get_field_id() method and get_field_name() method to create IDs and names for the form fields respectively. WordPress will generate unique identifiers for you so as not to clash with other widgets in use, and when the form is submitted the values will update the relevant $instance array items. You can use the passed $instance argument to populate the form fields with values should they already be set.
您使用WP_Widget的get_field_id()方法和get_field_name()方法分别为表单字段创建ID和名称。 WordPress将为您生成唯一的标识符,以免与正在使用的其他小部件冲突,并且在提交表单时,值将更新相关的$instance数组项。 您可以使用传递的$instance参数在表单域中填充已设置的值。
This is what the form looks like in the admin view:
这是该表单在admin视图中的外观:
The parent <form> element itself, the Save button, and the Delete and Close links are generated for you automatically by WordPress so there is no need to explicitly code them. The form will post the variables and call the update() method so the new values can be inserted into $instance.
WordPress会自动为您生成父<form>元素本身,“保存”按钮以及“删除”和“关闭”链接,因此无需对其进行显式编码。 表单将发布变量并调用update()方法,以便可以将新值插入$instance.
update() gives you an opportunity to validate and sanitize the instance variables before they are used by the widget. Here you can make decisions based on the old values and update the new values accordingly. update() must return an array which contains the items you expect to use when displaying the widget. WordPress passes two arguments to it, an array with the new instance values from the form, and an array with the original instance values.
update()使您有机会在小部件使用实例变量之前对其进行验证和清除。 在这里,您可以基于旧值进行决策,并相应地更新新值。 update()必须返回一个数组,其中包含您希望在显示小部件时使用的项目。 WordPress将两个参数传递给它,一个带有表单中新实例值的数组,以及一个带有原始实例值的数组。
<?php public function update($newInstance, $oldInstance) { $values = array(); $values["title"] = htmlentities($newInstance["title"]); $values["text"] = htmlentities($newInstance["text"]); return $values; }WordPress will persist these values for you so there is no need to implement that functionality.
WordPress将为您保留这些值,因此无需实现该功能。
The widget() method is used to display content within the widget when it appears in the sidebar on your blog. Output from the method will render the blog page. WordPress passes the widget() method two arguments: the first is $args which is an array detailing information about the widget, and the second is the $instance which you can use to get the output the data associated with the widget. $args really won’t affect this example so I won’t go into it; just remember $instance is the second argument.
当widget()方法出现在博客的侧边栏中时,将用于显示该widget中的内容。 该方法的输出将呈现博客页面。 WordPress传递了widget()方法两个参数:第一个是$args ,它是一个详细说明小部件信息的数组,第二个是$instance ,可用于获取与小部件关联的数据的输出。 $args确实不会影响此示例,因此我将不再赘述; 只要记住$instance是第二个参数。
<?php public function widget($args, $instance) { $title = $instance["title"]; $text = $instance["text"]; echo "<h2>$title</h2>"; echo "<p>$text</p>"; }This will produce the following possible output on the site:
这将在站点上产生以下可能的输出:
And that’s it! Putting all this together will give you a very simple widget to display text on the blog side of a WordPress installation.
就是这样! 将所有这些放在一起将为您提供一个非常简单的小部件,以在WordPress安装的博客侧显示文本。
You’re now familiar with the necessary groundwork for a WordPress plugin that ensures WordPress can detect and activate it, and extending the WP_Widget class to create your own widgets. The example widget presented in this article demonstrated the ability customize the widget’s display through an admin-provided configuration form. Though simple, it highlighted the basic WP_Widget methods you’ll use and you’ll easily be able to move on from this example and create greater functionality for your own WordPress driven sites. The code for this example is available under PHPMaster’s GitHub account so you can have a look at the code in it’s entirety.
您现在已经熟悉WordPress插件的必要基础,该插件可确保WordPress可以检测并激活它,并扩展WP_Widget类以创建自己的窗口小部件。 本文介绍的示例窗口小部件演示了通过管理员提供的配置表单自定义窗口小部件显示的功能。 尽管很简单,但它突出显示了您将使用的基本WP_Widget方法,并且您可以轻松地从该示例继续进行,并为自己的WordPress驱动的站点创建了更大的功能。 该示例的代码在PHPMaster的GitHub帐户下可用,因此您可以完整地查看代码。
Image via bioraven / Shutterstock
图片来自bioraven / Shutterstock
翻译自: https://www.sitepoint.com/wordpress-plugin-development/
wordpress插件开发
相关资源:WordPress插件开发全攻略(中文、英文和源码)