Table of Contents
start using
What are we doing?
Create plug-in library
What did we do?
Set shortcode
Storing plugin data in transient state
为什么要经历这一切?
显示插件信息
总结
付诸行动
显示有关插件的其他信息的示例简码
改进
接下来做什么?
Home CMS Tutorial WordPress Display information about WordPress.org plugins on your website

Display information about WordPress.org plugins on your website

Sep 03, 2023 pm 02:05 PM

在您的网站上展示 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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

Can I learn WordPress in 3 days? Can I learn WordPress in 3 days? Apr 09, 2025 am 12:16 AM

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

See all articles