wordpress插件开发_WordPress插件开发人员的10个必知技能

wordpress插件开发

WordPress is the most powerful CMS framework available at the moment. It can be used to create highly flexible and extendable websites with very little work. I believe that the Plugins and Themes structure is the main reason behind its success as a CMS. There are around 21,000 plugins available for free on the official WordPress website.

WordPress是目前可用的最强大的CMS框架。 它可以用于创建非常灵活且可扩展的网站,而无需花费太多工作。 我认为,插件和主题结构是其成功获得CMS的主要原因。 WordPress官方网站上约有21,000个免费插件。

I always prefer creating my own plugins whenever possible. I recommend you learn plugin development; you’ll be able to customize your site very easily and earn good money as a WordPress developer. In this article, I am going to discuss the most essential things you need to know about WordPress plugin development; I am assuming you have a basic knowledge of the WordPress folder structure here.

我总是喜欢尽可能地创建自己的插件。 我建议您学习插件开发; 您将能够非常轻松地自定义您的网站,并以WordPress开发人员的身份赚取丰厚的收入。 在本文中,我将讨论您需要了解的有关WordPress插件开发的最基本的知识; 我假设您对WordPress文件夹结构有基本的了解。

1.创建一个插件 (1. Creating a Plugin)

The first step will be creating your own plugin folder in the /wp-content/plugins folder. Once the folder is created you should place your plugin files inside that folder. You should have a main file for your plugin. Files should be named in simple letters with hyphens (-) for separating words.

第一步将在/ wp-content / plugins文件夹中创建您自己的插件文件夹。 创建文件夹后,应将插件文件放置在该文件夹中。 您应该为插件有一个主文件。 文件应以带连字符(-)的简单字母命名,以分隔单词。

  • Sample file name: wp-multi-slider.php

    示例文件名: wp-multi-slider.php

Inside your main file you should have the following comment structure in order for WordPress to identify your plugin.

在主文件中,您应该具有以下注释结构,以便WordPress识别您的插件。

<?php 

/* Plugin Name:  Sample Name 
Plugin URI: https://www.sitepoint.com/tutorials/wordpress-plugin-url 
Description: Get email notifications when your favorite author publishes a post. 
Version: 1.0 
Author URI: http://www.sitepoint.com 
Author: Rakhitha Nimesh 
License: GPL2 
*/

You will be able to see the plugin in the Dashboard Plugins section, as shown below.

您将能够在“仪表板插件”部分中看到该插件,如下所示。

alt

2.插件激活/停用 (2. Plugin Activation/Deactivation)

Plugins can be activated by clicking Activate Link in the plugin list. In a simple plugin you don’t need to do anything on activation. But an advanced plugin will require tasks like initializing plugin options, creating plugin tables, etc. So let’s see how we can handle plugin activation and deactivation.

可以通过在插件列表中单击“ 激活链接”激活插件。 在一个简单的插件中,您无需在激活时执行任何操作。 但是高级插件将需要诸如初始化插件选项,创建插件表等任务。因此,让我们看一下如何处理插件的激活和停用。

插件激活钩 (Plugin Activation Hook)

WordPress provides a function called register_activation_hook which will be triggered on plugin activation. We can add a custom function to execute on plugin activation using this method as shown below.

WordPress提供了一个名为register_activation_hook的功能,该功能将在插件激活时触发。 我们可以使用此方法添加一个自定义函数以使用该方法在插件激活时执行。

function wp_sample_activation() { 
} 
register_activation_hook(__FILE__, 'wp_sample_activation');

You have to pass the path of the file that contains the activation function as the first parameter and the function name as the second parameter.

您必须传递包含激活函数作为第一个参数和函数名称作为第二个参数的文件的路径。

If the activation function is inside the main plugin file you can use __FILE__  as shown in the above code. You can do tasks like validations, initializations and table creations inside the activation function.

如果激活功能在主插件文件中,则可以使用__FILE__ ,如上面的代码所示。 您可以在激活功能内执行验证,初始化和表创建之类的任务。

插件停用挂钩 (Plugin Deactivation Hook)

We can handle the deactivation of a plugin with register_deactivation_hook, using similar syntax as with activation. You can clean up the plugin resources, options and tables inside the deactivation function.

我们可以使用register_deactivation_hook处理插件的停用,该语法与激活类似。 您可以清除停用功能中的插件资源,选项和表。

function wp_sample_deactivation() { 

} 

register_deactivation_hook(__FILE__, 'wp_sample_deactivation');

3.创建自定义表 (3. Creating Custom Tables)

The WordPress database table structure is very flexible and you can implement most of the custom functionalities using the available tables. But there may be occasions where you wish to include more advanced systems like shopping carts, task management systems, or booking systems.

WordPress数据库表结构非常灵活,您可以使用可用表实现大多数自定义功能。 但是有时您可能希望包括更高级的系统,例如购物车,任务管理系统或预订系统。

In these cases, you need to know how and when to create custom tables. First, consider the requirements of your projects and try to use wp_options table and meta tables to store your project specific data. If you feel that the above tables are not structured enough to implement the required functionality, create custom tables using the following method.

在这些情况下,您需要知道如何以及何时创建自定义表。 首先,考虑项目的要求,并尝试使用wp_options表元表来存储项目的特定数据。 如果您认为上述表的结构不足以实现所需的功能,请使用以下方法创建自定义表。

global $wpdb; 
$wpdb->query("DROP TABLE IF EXISTS {$wpdb->prefix}sample_table"); 
$sql1 = "CREATE TABLE {$wpdb->prefix}sample_table ( id int(11) NOT NULL AUTO_INCREMENT, 
                                                       activation_code varchar(255) NOT NULL, 
                                                       email varchar(75) NOT NULL, 
                                                       status int(11) NOT NULL, PRIMARY KEY  (id) ) 
         ENGINE=InnoDB AUTO_INCREMENT=1;"; 

require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); 
dbDelta($sql1);

First, check if the table exists before creating it. You can decide to drop and create the table on activation based on your requirements. You can see that I have used {$wpdb->prefix} before the table name. Generally, WordPress tables are prefixed with wp_. . This can be changed when you install the database; so you should not hardcode wp_ as a prefix to provide increased flexibility.

首先,在创建表之前检查表是否存在。 您可以根据需要决定在激活时删除并创建表。 您可以看到我在表名之前使用了{$wpdb->prefix} 。 通常,WordPress表以wp_.为前缀wp_. 。 您可以在安装数据库时更改此设置。 因此,您不应将wp_硬编码为前缀以提供更大的灵活性。

{$wpdb->prefix} will you give you the prefix defined for the current installation. So always use that syntax before the new table name you are creating.

{$ wpdb-> prefix}会为您提供为当前安装定义的前缀。 因此,请始终在创建新表名称之前使用该语法。

Even though you can use the $wpdb->query function to create tables, it is recommended to use the dbDelta function as it compares the current table structure. It’s not loaded by default, so you need to include the file first.

即使可以使用$ wpdb-> query函数创建表,但还是建议使用dbDelta函数,因为它会比较当前的表结构。 默认情况下未加载该文件,因此您需要首先包含该文件。

4.包括脚本和样式 (4. Including Scripts and Styles)

Even though you can just echo the scripts and styles anywhere, it is recommended to add scripts using the wp_enqueue_script function. This function checks if the files are already available and also the dependencies with other scripts. The following example illustrates the effective use of wp_enque_script.

即使您可以在任何地方回显脚本和样式,也建议使用wp_enqueue_script函数添加脚本。 此功能检查文件是否已经可用以及与其他脚本的依赖关系。 以下示例说明了wp_enque_script.的有效用法wp_enque_script.

add_action('wp_enqueue_scripts', 'sample_scripts'); 

function sample_scripts() { 
  wp_enqueue_script('jquery'); 
  wp_register_style('sample_style', plugins_url('styles.css', __FILE__)); 
  wp_enqueue_style('sample_style'); 
  wp_register_script('jqueryUICore', plugins_url('ui/jquery.ui.core.js', __FILE__),array(“jQuery”)); 
  wp_enqueue_script('jqueryUICore'); 
  $config_array = array(“sample_name”=>”sample_value”]); 
  wp_localize_script('jqueryUICore', 'sampleData', $config_array); 
}

You can first use wp_register_style to register the style file and wp_enqueue_style to include the file. A unique identifier and path to the style file has to be provided. Then include scripts using the wp_enqueue_script function. If it depends on other scripts, you can mention it as the third parameter. I have used jQuery as a dependency.

您可以首先使用wp_register_style注册样式文件,并使用wp_enqueue_style包含文件。 必须提供样式文件的唯一标识符和路径。 然后使用wp_enqueue_script函数包含脚本。 如果它依赖于其他脚本,则可以将其作为第三个参数。 我已经使用jQuery作为依赖项。

Finally, you can add data to be used inside specific scripts by using the wp_localize_script function. You can include the scripts whenever you prefer, but always use the wp_enqueue_scripts and wp_enqueue_styles functions.

最后,您可以使用wp_localize_script函数添加要在特定脚本中使用的wp_localize_script 。 您可以随时包含脚本,但始终使用wp_enqueue_scriptswp_enqueue_styles函数。

Make sure to use the admin_enqueue_script action instead of wp_enqueue_script for the admin side.

确保在管理端使用admin_enqueue_script操作而不是wp_enqueue_script

5.创建简码 (5. Creating Shortcodes)

Shortcodes are predefined blocks of codes which you can use anywhere. It is vital to learn about shortcodes as a plugin developer, since you can add dynamic behavior to custom pages with them.

简码是预定义的代码块,您可以在任何地方使用。 作为插件开发人员,学习短代码至关重要,因为您可以使用它们向自定义页面添加动态行为。

You can create shortcodes using following syntax.

您可以使用以下语法创建简码。

add_shortcode("shortcode_name", "shortcode_function"); 
function shortcode_function() { 
  return “<input type=’button’ value=’Share’ /> “; 
}

Assign a shortcode name and function to the add_shortcode function. Then return the type of content you want to display in the browser inside the function. The above shortcode creates a simple HTML button.

add_shortcode代码名称和函数分配给add_shortcode函数。 然后返回要在功能内的浏览器中显示的内容的类型。 上面的短代码创建了一个简单HTML按钮。

Use the shortcode in pages, posts or plugins to display the button using the following syntax:

使用页面,帖子或插件中的简码,使用以下语法显示按钮:

[shortcode_name/]

[shortcode_name /]

6.过滤内容 (6. Filtering Content)

It is essential to consider how to filter post or page content when you develop a blog-related plugin. Consider the example below.

开发与博客相关的插件时,必须考虑如何过滤帖子或页面的内容。 考虑下面的示例。

function sample_content_filter($content) { 
  $banners = “HTML for banners”; 
  $author = “HTML for author info”; 
  return $banners.$content.$author; 
} 
add_filter( 'the_content', 'sample_content_filter' );

Every time a page or post is viewed, the content will be passed to the function. You can modify, add or remove content as I have shown above.

每次查看页面或帖子时,内容都会传递给函数。 您可以如上所述修改,添加或删除内容。

You can also use WordPress conditional tags to filter the content for specific pages. The following code filters the content on a post detail page.

您还可以使用WordPress条件标签来过滤特定页面的内容。 以下代码过滤帖子详细信息页面上的内容。

function sample_content_filter($content) {
  if(is_single()){ 
  return $banners.$content.$author; 
  } 
}

7.使用Ajax (7. Working with Ajax)

Ideally, you should know how to use Ajax in WordPress to provide interactive content for users. jQuery’s Ajax functionality is an easy way of mastering this.

理想情况下,您应该知道如何在WordPress中使用Ajax为用户提供交互式内容。 jQuery的Ajax功能是掌握此功能的简便方法。

$.post("admin-ajax.php", { action:"sample_ajax_action" }, 
function(result, textStatus) { 
}, "json");

The most important thing in the above Ajax request is the action. It will be used in the WordPress code to identify the request. Also, all the Ajax requests should be sent to the admin-ajax.php file.

上述Ajax请求中最重要的是操作。 它将在WordPress代码中用于识别请求。 另外,所有Ajax请求都应发送到admin-ajax.php文件。

function sample_ajax_action() { 
echo json_encode($your_result_array); exit; 
} 
add_action('wp_ajax_nopriv_sample_ajax_action', 'sample_ajax_action'); 
add_action('wp_ajax_sample_ajax_action', 'sample_ajax_action');

You can see the same action name used in Ajax is used here with wp_ajax_nopriv_ and wp_ajax_ prefixes. wp_ajax_ is used for logged-in users, and wp_ajax_nopriv_ is used for users who are not logged in.

您可以在此处看到与wp_ajax_nopriv_wp_ajax_前缀一起使用的Ajax中使用的相同操作名称。 wp_ajax_用于登录的用户, wp_ajax_nopriv_用于未登录的用户。

8.编写SQL查询 (8. Writing SQL Queries)

In WordPress, we have to consider the security of our queries in order to prevent SQL injections. We can use the prepare method to filter the user data before applying it to the query. Always filter user-submitted data with the following code before processing.

在WordPress中,我们必须考虑查询的安全性,以防止SQL注入。 在将其应用于查询之前,我们可以使用prepare方法过滤用户数据。 在处理之前,请始终使用以下代码过滤用户提交的数据。

$wpdb->query($wpdb->prepare("update wp_sample_table set status=1 where activation_code=%s and status=%d",$activationCode,$status));

As shown above, always assign escape characters to the SQL and variable values at the end to filter the data before executing in SQL.

如上所示,请始终在SQL末尾分配转义字符和变量值,以在使用SQL执行之前过滤数据。

9.添加选项框 (9. Adding Option Boxes)

WordPress provides a default set of fields such as title, content, image, and excerpt in the content creation screen. We need custom fields to add additional behavior. Even though we can use the custom fields section, it provides text boxes only. We need to add separate fields if we require checkboxes, radio buttons, drop downs and the like.

WordPress在内容创建屏幕中提供了一组默认字段,例如titlecontentimage摘录 。 我们需要自定义字段来添加其他行为。 即使我们可以使用“自定义字段”部分,它也仅提供文本框。 如果需要复选框,单选按钮,下拉菜单等,我们需要添加单独的字段。

We can easily create option boxes to provide additional fields, as shown below.

我们可以轻松地创建选项框以提供其他字段,如下所示。

add_action('add_meta_boxes', 'add_custom_fields_box'); 
function add_custom_fields_box() { 
  add_meta_box('custom_fields_box_id', 'Custom Info', 'display_custom_info_box', 'post', 'normal', 'high'); 
} 

function display_custom_info_box() { 
global $post; 
$html = "<table><tr><td>Custom Checkbox</td><td><input id='custom_checkbox' type='checkbox' name='custom_checkbox'  /></td></tr> <tr><td>Custom Selecy</td><td><select name='custom_select'  > <option>Option 1</option> </select></td></tr> <tr><td>Custom Upload</td><td><input id='custom_file' type='file' name='custom_file'  /></td></tr></table>"; 

echo $html; 

}

Values of the fields will be saved to the wp_options table as custom fields. You should prefix your option field names with an underscore to prevent duplication with the custom fields section.

这些字段的值将作为自定义字段保存到wp_options表中。 您应该在选项字段名称前加上下划线,以防止与“自定义字段”部分重复。

10.使用Nonnce进行插件安全性 (10. Using Nonces for Plugin Security)

Security is major concern in creating WordPress plugins. You should not trust data provided by users, and you always need to validate data before executing. WordPress provides a concept called a nonce which creates a nonce value, or arbitrary number used only once, when a form is generated. Then we can check for the same nonce value once the form is submitted to ensure it is a valid request — or otherwise.

安全是创建WordPress插件的主要问题。 您不应该信任用户提供的数据,并且始终需要在执行之前验证数据。 WordPress提供了一个称为随机数的概念,当生成表单时,该概念会创建一个随机数值或仅使用一次的任意数字。 然后,一旦提交表单,我们就可以检查相同的现时值,以确保它是有效的请求-否则。

You can create a nonce value using the following code:

您可以使用以下代码创建现时值:

wp_nonce_field('sample_frm_nonce', 'sample_frm_nonce');

The first parameter is a unique identifier and the second parameter will be used as hidden form field name. Once the form is submitted, you can validate the nonce value using the code below.

第一个参数是唯一标识符,第二个参数将用作隐藏的表单字段名称。 提交表单后,您可以使用以下代码验证现时值。

if (!isset($_POST['sample_frm_nonce']) || !wp_verify_nonce($_POST['sample_frm_nonce'], 'sample_frm_nonce')){
  return; 
}

If the nonce is not validated, the request is not processed further.

如果随机数未通过验证,则不会进一步处理该请求。

The WordPress Plugin API is huge, and it is not easy to to cover everything it involves. What I’ve gone through here are just the 10 most common things you might need in the act of plugin creation. Feel free to suggest more concepts you might want to take into account as a plugin developer.

WordPress插件API非常庞大,要覆盖它涉及的所有内容并不容易。 我在这里所做的只是在创建插件时可能需要的10个最常见的事情。 随意建议您作为插件开发人员可能要考虑的更多概念。

翻译自: https://www.sitepoint.com/10-must-know-skills-for-a-wordpress-plugin-developer/

wordpress插件开发

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值