wordpress创建

Have you tried to find functionality for a specific purpose in WordPress but failed to find a plugin or widget that does your work? This post walks through how you can create a WordPress widget, even if you have limited knowledge of coding.

您是否尝试过在WordPress中找到用于特定目的的功能,但是找不到适合您的工作的插件或小部件? 即使您对编码的知识有限,本文也会逐步介绍如何创建WordPress小部件。

WordPress Widgets are blocks of code — static, dynamic, or a combination of both — which can be added to any specific area of your WordPress site. There are many built-in widgets in WordPress — such as tag cloud and categories — but this post helps you create a widget from scratch in a short time. It will probably take you longer to finish reading this article than to create the widget after you gain the knowledge!

WordPress窗口小部件是代码块(静态,动态或二者的结合),可以将其添加到WordPress网站的任何特定区域。 WordPress中有许多内置小部件(例如标签云和类别),但是这篇文章可帮助您在短时间内从头开始创建小部件。 获得知识之后,完成阅读本文所需的时间可能比创建窗口小部件要花费更多的时间!

For illustration purposes, we’re looking at creating a widget with dynamic content in the form of real time data of cricket matches. The purpose of creating dynamic content is to familiarize you with various functions that are associated with WordPress Widgets.

出于说明目的,我们正在考虑以板球比赛的实时数据形式创建具有动态内容的小部件。 创建动态内容的目的是使您熟悉与WordPress小部件相关的各种功能。

前提条件 (Pre Requisites)

Before you start any code, please make sure you back up your WordPress code, as you may end up with a white screen of death. Alternately, you may want to explore version control for WordPress with Git.

在开始任何代码之前,请确保备份WordPress代码 ,否则可能会死机。 或者,您可能希望使用Git探索WordPress的版本控制 。

Further, it’s recommended that you have some knowledge of OOP in PHP before attempting to create a widget.

此外,建议您在尝试创建小部件之前对PHP的OOP有一定的了解。

This tutorial has been created on WordPress version 4.9.8.

本教程是在WordPress 4.9.8版上创建的。

将代码放在哪里? (Where to Put the Code?)

Before we discuss the nuances of developing a WordPress Widget, let’s consider where to keep the code. The answer to that lies in the purpose for developing the widget. In case you want the widget to appear in a specific theme only, you can put the code in the theme’s functions.php file. However, this makes the widget accessible only if the theme is active.

在讨论开发WordPress小部件的细微差别之前,让我们考虑将代码保存在何处。 答案在于开发小部件的目的。 如果您希望小部件仅出现在特定主题中,则可以将代码放在主题的functions.php文件中。 但是,这仅在主题处于活动状态时才使小部件可访问。

This tutorial focuses on creating a widget which can be accessed throughout themes on your website. Hence, we would create a new plugin, which houses the widget that shows a list of live cricket matches from an API.

本教程着重于创建一个可在您网站上的整个主题中访问的窗口小部件。 因此,我们将创建一个新插件,其中包含显示来自API的实时板球比赛列表的小部件。

小部件开发基础 (Widget Development Basics)

To create a widget in WordPress, you need to extend the WP_Widget class. Within your widget class, you can create a list of functions:

要在WordPress中创建小部件,您需要扩展WP_Widget类。 在窗口小部件类中,您可以创建函数列表:

  • the constructor function构造函数
  • the widget function to display the widget contents

    widget功能以显示小部件内容

  • the form function if you need to define a form that takes input

    form函数,如果您需要定义一个接受输入的表单

  • the update function if you need to update the settings of the widget.

    如果您需要更新小部件的设置,请使用update功能。

In the example of displaying cricket feeds, we need to define only the first two functions. Further, once we’ve created the widget class, we need to register it with the register_widget function.

在显示板球提要的示例中,我们仅需要定义前两个功能。 此外,一旦创建了窗口小部件类,就需要使用register_widget函数对其进行register_widget

Let’s now move on to creating a basic plugin in WordPress and then use an API to generate dynamic content.

现在,让我们继续在WordPress中创建一个基本插件,然后使用API​​生成动态内容。

基础:Hello World小部件 (The Basics: Hello World Widget)

Before you create the widget, an empty plugin needs to be created. Head on to the /wp-content/plugins/ and create a new directory with the slug of the name of your plugin. Within this directory, create an index.php file with the following content.

在创建窗口小部件之前,需要创建一个空插件。 转到/wp-content/plugins/并使用插件名称的标签创建一个新目录。 在此目录中,创建具有以下内容的index.php文件。

定义一个空插件 (Define an Empty Plugin)

<?php
/*
Plugin Name: Live Score Custom
Plugin URI: https://www.sitepoint.com/
Description: Get and display sports feeds
Version: 1.0
Author: Shaumik
Author URI: https://www.sitepoint.com/
License: GPL2
*/
?>

This is essentially a blank PHP file with comments, as suggested on the WordPress Codex page on creating a new plugin. These comments are read by WordPress when displaying information about the plugin on WP Admin.

本质上是一个空白PHP文件,带有注释,如创建新插件的WordPress Codex页面上所建议。 当在WP Admin上显示有关插件的信息时,WordPress将阅读这些注释。

Once you’ve created the empty plugin with comments, you can see that your plugin is active on the list of plugins on WP Admin. Activate the plugin before proceeding further.

创建带有注释的空插件后,您可以在WP Admin上的插件列表中看到该插件处于活动状态。 在继续操作之前,请激活插件。

Plugin list on WP Admin after creating empty plugin 创建空插件后,WP Admin上的插件列表

在插件中定义窗口小部件 (Define a Widget within the Plugin)

The next step is to create a sample widget code. As discussed earlier, we would be extending the WP_Widget class. After defining the class, we’ll register the widget using the register_widget method:

下一步是创建示例窗口小部件代码。 如前所述,我们将扩展WP_Widget类。 定义了类之后,我们将使用register_widget方法注册小部件:

class My_Custom_Widget extends WP_Widget {
public function __construct() {
}
public function widget( $args, $instance ) {
// Define the widget
}
}
// Register the widget
function my_register_custom_widget() {
register_widget( 'My_Custom_Widget' );
}
add_action( 'widgets_init', 'my_register_custom_widget' );

Now that our skeleton code is ready, let’s fill in the constructor and widget functions:

现在我们的框架代码已经准备好,让我们填写构造函数和widget函数:

public function __construct() {
// Define the constructor
$options = array(
'classname' => 'custom_livescore_widget',
'description' => 'A live score widget',
);
parent::__construct(
'live_score_widget', 'Live Score Widget', $options
);
}

The constructor can be extended from the parent constructor. In the options, we can also provide a CSS class that’s added to the entire widget element in the HTML DOM when being displayed. Next, let’s define the widget display options:

构造函数可以从父构造函数扩展。 在选项中,我们还可以提供一个CSS classclass在显示时会添加到HTML DOM中的整个小部件元素中。 接下来,让我们定义小部件显示选项:

public function widget( $args, $instance ) {
// Keep this line
echo $args['before_widget'];
echo $args['before_title'] . apply_filters( 'widget_title', 'Live Criket Matches' ) . $args['after_title'];
echo 'Hello, World!';
// Keep this line
echo $args['after_widget'];
}

In the widget class, we define what needs to be displayed in the widget. First, we add a widget title, “Live Cricket Matches”, and then a simple “Hello, World!”

widget类中,我们定义需要在小部件中显示的内容。 首先,我们添加一个小部件标题“ Live Cricket Matches”,然后添加一个简单的“ Hello,World!”。

Once the code has been saved, let’s head back to Appearance > Widgets in WP Admin and add the newly created widget to a part of the page.

保存代码后,让我们回到WP Admin中的“ 外观”>“小部件” ,然后将新创建的小部件添加到页面的一部分。

Adding Widget in WP Admin 在WP Admin中添加小部件

Once you’ve added the widget, you can refresh your home page and check if the widget has appeared.

添加窗口小部件后,您可以刷新主页并检查窗口小部件是否已出现。

Hello World widget in the home page 主页中的Hello World小部件

You may notice that the class in which we defined the widget has been added to the widget element. You can change the style of the widget if required. If you’re interested, check out this tutorial on how to customize the style of a WordPress theme.

您可能会注意到,我们在其中定义窗口小部件的类已添加到窗口小部件元素中。 您可以根据需要更改小部件的样式。 如果您有兴趣,请查看本教程,了解如何自定义WordPress主题的样式 。

添加实时比分选项 (Adding a Live Score Option)

So far, we’ve successfully created a widget associated with a plugin, registered it on WP Admin and displayed it on our home page. The next step is to get the live score feed from an API.

到目前为止,我们已经成功创建了一个与插件相关联的小部件,并在WP Admin上注册了该小部件,并将其显示在我们的主页上。 下一步是从API获取实时比分Feed。

As a demonstration, we’ll use the API by CricAPI. You can make 100 API requests per day under the free plan. After registering, you’re provided with an API key, which is needed when you make requests to the site. We’ll use the “New match API” option to get the data for our widget.

作为演示,我们将使用CricAPI的API。 免费计划下,您每天可以发出100个API请求。 注册后,会为您提供一个API密钥,当您向该网站提出请求时需要使用它。 我们将使用“新匹配API”选项来获取小部件的数据。

A GET request needs to be sent to the Match API with the apikey parameter to get a list of matches. Once you have your API key you can verify that the API is working properly by going to the following URL on your browser:

需要使用apikey参数将GET请求发送到Match API以获取匹配项列表。 拥有API密钥后,您可以转到浏览器上的以下URL,以验证API是否正常运行:

http://cricapi.com/api/matches?apikey=api_key

The response is a JSON string, with the list of matches and some metadata. We can emulate the request and extract the data in PHP by modifying our widget function:

响应是一个JSON字符串,其中包含匹配项列表和一些元数据。 我们可以通过修改widget函数来模拟请求并提取PHP中的数据:

public function widget( $args, $instance ) {
// before and after widget arguments are defined by themes
echo $args['before_widget'];
echo $args['before_title'] . apply_filters( 'widget_title', 'Live Criket Matches' ) . $args['after_title'];
// This is where you run the code and display the output
$api_key = 'ONkuR4grRDFyUzOEYoSzeUQolbx2'
$api_url  = "http://cricapi.com/api/matches?apikey=" . $api_key;
//  Initiate curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $api_url);
// Execute
$result = curl_exec($ch);
// Closing
curl_close($ch);
// Will dump a json - you can save in variable and use the json
$cricketMatches = json_decode($result);
foreach($cricketMatches->matches as $item) {
if ($item->matchStarted == true) {
echo $item->{'team-1'}, ' vs ', $item->{'team-2'}, '<br />';
}
}
echo $args['after_widget'];
}

Here are the steps we follow in the code:

这是我们在代码中遵循的步骤:

  • we send a request to the URL through cURL, disabling the secure option (notice that the cricAPI URL is http)

    我们通过cURL发送请求到URL,禁用安全选项(注意cricAPI URL是http )

  • we save the JSON response after decoding in the variable $cricketMatches

    我们将解码后的JSON响应保存在变量$cricketMatches

  • we get a list of matches and display those which have started already.我们会得到一个匹配列表,并显示已经开始的匹配。

Let’s now have a look at the home page to see whether the desired data is shown.

现在让我们看一下主页,看看是否显示了所需的数据。

Widget displaying list of cricket matches in home page 显示主页上板球比赛列表的小部件

The data can be explored further to display specific options. For instance, you can get the score by sending a request to the cricket score API with your API key and match ID.

可以进一步探索数据以显示特定选项。 例如,您可以通过使用API​​密钥和匹配ID向板球比分API发送请求来获得比分 。

打包和共享插件 (Packaging and Sharing the Plugin)

There you go. You’ve successfully created the widget that lists live cricket matches! You can pack the plugin by creating a zip file of the live-score-custom-plugin directory, and uploading the zip file to Plugins > Add New > Upload Plugin.

妳去 您已经成功创建了列出实时板球比赛的小部件! 您可以通过创建live-score-custom-plugin目录的zip文件并将该zip文件上传到Plugins> Add New> Upload Plugin来打包插件

最后的想法 (Final Thoughts)

In this tutorial, we went through the basics of creating a widget in WordPress through a plugin and extracted live sports feeds to display data.

在本教程中,我们介绍了通过插件在WordPress中创建窗口小部件的基础知识,并提取了实时体育供稿以显示数据。

翻译自: https://www.sitepoint.com/create-wordpress-widget/

wordpress创建

wordpress创建_十分钟即可在WordPress中创建动态小部件相关推荐

  1. extjs中滚动条属性_十分钟快速了解 JS 中的 offset、scroll、client

    (给前端大全加星标,提升前端技能) 作者:前端下午茶 公号 /  SHERlocked93 在下开发中经常碰到 offset.scroll.client 这几个关键字,比如 offsetLeft.of ...

  2. .net label在父容器中占两行显示_十分钟快速了解 JS 中的 offset、scroll、client

    经常碰到offset.scroll.client这几个关键字,每次都要各种实验,这里总结一下. 两张图镇楼,随时翻阅 1. offset offset 指偏移,包括这个元素在文档中占用的所有显示宽度, ...

  3. Bee框架,一个十分钟即可学会的ORM框架--Bee

    Bee 是一个ORM框架.关注:省时/优雅.简易.自动( Tea: Timesaving/Tasteful, Easy, Automatic) 特性.减少开发人员的编码量,只为一个目标--让别人不再叫 ...

  4. 在idea中创建mybatis-config.xml模板(在idea中创建mybatis核心配置文件模板)

    在idea中创建mybatis-config.xml模板(在idea中创建mybatis核心配置文件模板) 1.写配置文件 2.设置 3.查看 1.写配置文件 先创建一个mybatis-config. ...

  5. a.创建动物类Animal,在该类中创建一个成员方法cry(), 输出“动物会发出叫声”,以及一个eat()方法,输出“动物需要食物”; b.创建一个Animal子类Dog类,在该类中重写父类的成员

    创建Zoo类作为主类,在main方法中分别创建各个类对象 ,并调用各自类的cry()方法, 创建Dog类的对象赋值给Animal类的对象,然后调用cry()和eat()方法. ** a.创建动物类An ...

  6. 创建视图SQL:在SQL Server中创建视图

    介绍 (Introduction) In this article, we are going to see how to use the CREATE VIEW SQL statement to c ...

  7. wordpress插件_深入了解:高级WordPress插件

    随着WordPress的发布,它是开源平台的第三次(第三次)主要迭代,我们已经看到越来越多的开发人员蜂拥而至, 大规模发布了插件. 尽管插件的免费选项似乎层出不穷,但是有些软件公司以非常实惠的价格提供 ...

  8. wordpress使用_如何使用SearchWP改进WordPress搜索

    wordpress使用 WordPress is a great content management system, but the default WordPress search feature ...

  9. 逗号后面统一加空格_十分钟搞定字幕,教你做加字幕的“快手菜”

    平台上许多同学有疑问:做视频是否有加字幕的必要呢? 其实除了外语需要翻译.语速过快加字幕方便理解.普通话不标准等情况之外,还是建议有余力的同学可以加上字幕,提升用户的观看体验. 那么问题来了,存在以下 ...

最新文章

  1. 小撒、金晨都想拥有!百度全球首款汽车机器人亮相,车内躺着看星星
  2. JAVA第一个GUI程序---计算器
  3. javascript - 你不容错过的es6模板写法
  4. 5G 十项全能、搭载麒麟 820 芯片,1899 元起的荣耀 X10 来了!
  5. 屏蔽五项网络功能 让XP系统极速狂飙
  6. Android IntentService的使用与源码解析
  7. 【游戏开发】免费开源游戏引擎
  8. SVG 与 Canvas:如何选择
  9. linux离线安装pg数据库
  10. mysql命令导出表结构和数据_mysql命令导入\导出表结构或数据
  11. BLEU——机器翻译评测
  12. 支付宝——手机网站支付接口研究
  13. Youtube 视频下载
  14. 微信公众平台开发者配置
  15. 计算机应用基础文章 茶的功效,【课程改革论文】茶文化下的计算机应用基础教程课程改革(共5535字)...
  16. uniapp--动态背景特效1
  17. matlab 色温图,技术:图文教你了解色温及如何选择色温
  18. 数据分析------统计学----小样本容量置信区间例题
  19. 初入计算机专业,编程语言怎么选?大学生活如何度过?
  20. 程序文件分类及编写要求

热门文章

  1. 冰蝎3.0的使用方法与默认密码更改方法
  2. 如何通过linux下载github代码
  3. QPainter QPixmap 抗锯齿
  4. 使用正则表达式把IM聊天中的自定义表情格式转换成表情图片
  5. 计算机基础知识菜鸟教程,菜鸟教程:改造最基础知识 电工基础
  6. 护肤的正确步骤 女性正确护肤步骤
  7. 初夏基础护肤,步骤一定要做对!
  8. 电脑硬盘文件数据误删除/格式化为什么可以恢复? 怎么恢复?谈谈文件删除与恢复背后的原理
  9. 一次对K8S集群service的“非主流”访问方式引发的网络探究
  10. 地铁线路查询系统的设计与实现