Home > CMS Tutorial > WordPress > Display information about WordPress.org plugins on your website

Display information about WordPress.org plugins on your website

PHPz
Release: 2023-09-03 14:05:06
Original
1162 people have browsed it

在您的网站上展示 WordPress.org 插件的信息

In the first part of this article, we discussed how to use built-in functions to communicate with WordPress.org and retrieve plugin details.

In this tutorial we will put theory into practice and create a simple plugin that will allow us to display the details of any plugin hosted on WordPress.org on our WordPress website using shortcodes. p>


start using

I assume you are a plugin developer and know the basics, but if in doubt I recommend reading the following two articles:

  • Two approaches to developing WordPress plugins: Functional programming
  • Two approaches to developing WordPress plugins: Object-oriented programming

What are we doing?

With this plugin, we want to create a shortcode, such as [mpi slug='my-plugin-information' field='version'], which can accept two attributes: "slug" and "field", then based on that, we retrieve and display information for any plugins hosted in the WordPress.org repository.

Create plug-in library

Let’s start by creating a folder called my-plugin-information inside the wp-content/plugins directory. Create a file inside it called my-plugin-info.php and paste the following code into it:

<?php
/*
Plugin Name: My Plugin Info
Plugin URI: https://myplugininfo.com
Description: Communicate with WordPress.org Plugins API to retrive your Plugin Information
Version: 0.1
Author: Harish
Author Email: mye@email.com
License: GPL3
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

if ( ! class_exists( 'DOT_MyPluginInfo' ) )
{

	class DOT_MyPluginInfo {

		/**
		 * Constructor
		 */
		function __construct() {

			//Hook up to the init action
			add_action( 'init', array( &$this, 'init_my_plugin_info' ) );

		}

		/**
		 * Runs when the plugin is initialized
		 */
		function init_my_plugin_info() {

			// Register the shortcode [mpi slug='my-plugin-info' field='version']
			add_shortcode( 'mpi', array( &$this, 'render_mpi' ) );

		}

		function render_mpi($atts) {

		}

	} // end class

	new DOT_MyPluginInfo();
}
?>
Copy after login

What did we do?

In the above code, we create and initialize the plug-in class DOT_MyPluginInfo. This contains common blocks for any plugin, such as the __construct() method.

Function init_my_plugin_info Hooks into the init action so that it runs after WordPress is loaded but before any headers are sent. In the function init_my_plugin_info we register our shortcode using the add_shortcode function.

Note: To learn more about add_shortcode, check out the Codex.

The above plugin now has enough code to be recognized by WordPress from the plugin dashboard. If you have followed the instructions to create the file, you can now visit the Plugins page and activate this plugin.


Set shortcode

Since we wanted the flexibility to choose what information to display about the plugin, we created a shortcode with two properties. The first one called "slug" will be used to specify which plugin's data needs to be retrieved. The second attribute "field" will be used to specify the specific information of the plugin we need to display.

For example, if we wanted to display the number of downloads of the plugin, we would simply add text below the post editor, and the end result should be something like "Downloaded 100 times."

Downloaded [mpi slug='my-plugin-information' field='downloaded'] times.
Copy after login

Using add_shortcode we register our shortcode so that whenever the shortcode is found within the post content, the function render_mpi() is called to handle it. From now on, the rest of the code will be placed inside this function to handle our shortcode.

Use render_mpi() to process shortcodes

To display plugin information, we first need to process the shortcode to get the attributes. Add the following code in the render_api function:

// get our variable from $atts
extract( shortcode_atts( array(
	'slug' => '', //foo is a default value
	'field' => ''
), $atts ) );
Copy after login

This extracts the two properties "slug" and "field" (if provided). Before proceeding, we first check if the values ​​of "slug" and "field" exist, if not, stop further processing.

/**
 * Check if slug exists
 */
if ( ! $slug ) {
	return false;
}

/**
 * Check if field exists
 * Return value based on the field attribute
 */
if ( ! $field ) {
	return false;
} else {

} // $field check
Copy after login

The above code will check whether "slug" exists and return false if it does not exist. If "slug" does exist, it will continue to check the "field" attribute. Since we are just creating a shortcode to display specific information about the plugin, checking for the presence of these two properties before processing further will save unnecessary calls to the WordPress.org plugin API.

Now, if values ​​for the "slug" and "field" attributes are provided in the shortcode, we will clean these two values ​​first.

// Sanitize attributes
$slug = sanitize_title( $slug );
$field = sanitize_title( $field );
Copy after login

Storing plugin data in transient state

To avoid sending a request to WordPress.org every time a page containing this shortcode is loaded, we need to save the plugin information locally. This way, if you place multiple shortcodes that display different details for the same plugin, we can speed up the process by displaying data from locally saved information on your site.

But what if the plugin updates and we keep showing old data? To solve this problem, the quickest option is to use the Transients API to save our personal plugin data and set the expiration date data.

Another issue is if you have shortcodes that are retrieving data about different plugins. If we store them using a single temporary name, the results may be unexpected. To solve this problem, we use the "slug" attribute to give the saved transient a unique name.

为什么要经历这一切?

  • 单独保存每个插件的信息
  • 减少向 WordPress.org 发出的请求
  • 通过直接从您自己的网站提供数据来更快地加载数据

让我们首先创建一个变量 $mpi_transient_name 来保存基于“slug”属性的唯一瞬态名称。

// Create a empty array with variable name different based on plugin slug
$mpi_transient_name = 'mpi-' . $slug;
Copy after login

接下来我们检查瞬态是否已经存在:

/**
 * Check if transient with the plugin data exists
 */
 $mpi_info = get_transient( $mpi_transient_name );
Copy after login

如果瞬态存在,我们将继续根据“field”属性显示数据,否则我们使用 plugins_api 连接到 WordPress.org 并请求插件信息。

if ( empty( $mpi_info ) ) {

	/**
	 * Connect to WordPress.org using plugins_api
	 * About plugins_api -
	 * https://code.tutsplus.com/tutorials/communicating-with-the-wordpress-org-plugin-api--wp-33069
	 */
	require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
	$mpi_info = plugins_api( 'plugin_information', array( 'slug' => $slug ) );

	// Check for errors with the data returned from WordPress.org
	if ( ! $mpi_info or is_wp_error( $mpi_info ) ) {
		return false;
	}

	// Set a transient with the plugin data
	// Use Options API with auto update cron job in next version.
	set_transient( $mpi_transient_name, $mpi_info, 1 * HOUR_IN_SECONDS );

}
Copy after login

在上面的代码中,我们做了三件事:

  1. 我们连接到 WordPress.org 并请求插件信息。然后该请求被保存在名为 $mpi_info 的变量中
  2. 然后我们进行错误检查,以确保返回的数据是否没有错误
  3. 最后,我们创建了一个过期日期为一小时的新瞬态

现在,如果 slug 属性的值为“my-plugin-information”,那么存储插件信息的瞬态名称将为“mpi-my-plugin-information”。

注意:要了解有关 plugins_api 的更多信息,请参阅本系列的第一篇文章,如本文顶部所示。

显示插件信息

最后一步涉及根据“field”属性的值返回特定信息。为此,我们只需使用单独的检查即可。

if ( $field == "downloaded" ) {
	return $mpi_info->downloaded;
}

if ( $field == "name" ) {
	return $mpi_info->name;
}

if ( $field == "slug" ) {
	return $mpi_info->slug;
}

if ( $field == "version" ) {
	return $mpi_info->version;
}

if ( $field == "author" ) {
	return $mpi_info->author;
}

if ( $field == "author_profile" ) {
	return $mpi_info->author_profile;
}

if ( $field == "last_updated" ) {
	return $mpi_info->last_updated;
}

if ( $field == "download_link" ) {
	return $mpi_info->download_link;
}
Copy after login

总结

完整的插件代码:

<?php
/*
Plugin Name: My Plugin Information
Plugin URI: https://code.tutsplus.com
Description: Communicate with WordPress.org Plugins API to retrive your Plugin Information
Version: 0.1.1
Author: Harish
Author Email: me@email.com
License:

  Copyright 2013 Harish

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 3, 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

*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

if ( ! class_exists( 'DOT_MyPluginInfo' ) )
{

	class DOT_MyPluginInfo {

		/**
		 * Constructor
		 */
		function __construct() {

			//Hook up to the init action
			add_action( 'init', array( &$this, 'init_my_plugin_info' ) );

		}

		/**
		 * Runs when the plugin is initialized
		 */
		function init_my_plugin_info() {

			// Register the shortcode [mpi slug='my-plugin-info' field='version']
			add_shortcode( 'mpi', array( &$this, 'render_mpi' ) );

		}

		function render_mpi($atts) {

			// get our variable from $atts
			extract(shortcode_atts(array(
				'slug' => '', //foo is a default value
				'field' => ''
			), $atts));

			/**
			 * Check if slug exists
			 */
			if ( ! $slug ) {
				return false;
			}

			/**
			 * Check if field exists
			 * Return value based on the field attribute
			 */
			if ( ! $field ) {

				return false;

			} else {

				// Sanitize attributes
				$slug = sanitize_title( $slug );
				$field = sanitize_title( $field );

				// Create a empty array with variable name different based on plugin slug
				$mpi_transient_name = 'mpi' . $slug;

				/**
				 * Check if transient with the plugin data exists
				 */
				$mpi_info = get_transient( $mpi_transient_name );

				if ( empty( $mpi_info ) ) {

					/**
					 * Connect to WordPress.org using plugins_api
					 * About plugins_api -
					 * https://code.tutsplus.com/tutorials/communicating-with-the-wordpress-org-plugin-api--wp-33069
					 */
					require_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
					$mpi_info = plugins_api( 'plugin_information', array( 'slug' => $slug ) );

					// Check for errors with the data returned from WordPress.org
					if ( ! $mpi_info or is_wp_error( $mpi_info ) ) {
						return false;
					}

					// Set a transient with the plugin data
					// Use Options API with auto update cron job in next version.
					set_transient( $mpi_transient_name, $mpi_info, 1 * HOUR_IN_SECONDS );

				}

				if ( $field == "downloaded" ) {
					return $mpi_info->downloaded;
				}

				if ( $field == "name" ) {
					return $mpi_info->name;
				}

				if ( $field == "slug" ) {
					return $mpi_info->slug;
				}

				if ( $field == "version" ) {
					return $mpi_info->version;
				}

				if ( $field == "author" ) {
					return $mpi_info->author;
				}

				if ( $field == "author_profile" ) {
					return $mpi_info->author_profile;
				}

				if ( $field == "last_updated" ) {
					return $mpi_info->last_updated;
				}

				if ( $field == "download_link" ) {
					return $mpi_info->download_link;
				}

			} // $field check

		} // render_mpi()

	} // end class
	new DOT_MyPluginInfo();

}

?>
Copy after login

此插件代码可在 GitHub 上找到,您也可以从 WordPress.org 下载


付诸行动

现在您只需转到帖子编辑器并添加一个短代码,例如:

Downloaded &#91;mpi slug='my-plugin-information' field='downloaded'&#93; times.
Copy after login

它会显示:

Downloaded 10 times.
Copy after login

显示有关插件的其他信息的示例简码

通过替换“field”属性的值,您可以显示不同的信息,例如:

  • 插件名称:[mpi slug='my-plugin-information' field='name']
  • 插件版本:[mpi slug='my-plugin-information' field='version']
  • 插件 Slug:[mpi slug='my-plugin-information' field='slug']
  • 插件作者(返回名称和链接):[mpi slug='my-plugin-information' field='author']
  • 作者简介(返回个人资料地址):[mpi slug='my-plugin-information' field='author_profile']
  • 最后更新:[mpi slug='my-plugin-information' field='last_updated']
  • 下载链接:[mpi slug='my-plugin-information' field='download_link']

改进

为了简单起见,我使用瞬态来保存插件信息。然而,瞬态从来就不是用来保存重要数据的。另一种方法是使用选项 API、add_options() 或作为 post meta 保存插件数据,然后安排一个 cron 任务每小时更新一次数据。


接下来做什么?

使用 plugins_api,我们已经演示了通信和检索 WordPress.org 上托管的任何插件的信息是多么容易。

您可能还想查看其他插件,例如 Plugin Info(也使用 plugins_api 和 I Make Plugins,看看它们如何完成相同的任务。

The above is the detailed content of Display information about WordPress.org plugins on your website. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template