Table of Contents
Theme function: Invasion of plug-in territory
Introduction to TGM plug-in activation library
Install TGM plug-in activation
Activate and install the plug-in through TGM plug-in
需要 WordPress.org 的插件
从外部源请求插件
从主题目录中获取插件
配置 TGM 插件激活
总结一切
Home CMS Tutorial WordPress Leverage the power of the TGM plugin activation library in your theme

Leverage the power of the TGM plugin activation library in your theme

Sep 01, 2023 pm 10:49 PM

在您的主题中利用 TGM 插件激活库的强大功能

Themes are not meant to be functional, but as theme developers we mainly need to include some features to make our themes a little better and functional.

In this tutorial we will learn about the term "plugin realm" and learn to use an excellent tool written by Thomas Griffin: the TGM plug-in activation library.

Theme function: Invasion of plug-in territory

Themes are designed to change the design of your WordPress website. Ideally it should be visual. But in the golden age of WordPress, theme developers often included functional features in their themes to stay competitive in the market. It should be so, but it is.

This is an invasion of plugin territory. We can define "plugin domain" in simple terms: the functional part of the code lies within the boundaries of the domain. Every piece of code that changes the functionality of your website needs to be available as a plugin (if it’s not already available in WordPress core).

In one of my previous articles (in the "Making the Perfect WordPress Theme" series), I mentioned a rule of thumb in the "plugin world":

If the feature is related to the visual appearance of the site, it should be in the theme, but if it is related to the functionality of the site, it should be in the theme as a separate Plug-ins are included.

Pretty simple, right?

Although people still tend to hardcode feature bits into their themes, theme directories (such as WordPress.org and ThemeForest) do not accept themes that invade the "plugin realm". Therefore, providing functionality with themes becomes a problem.

Fortunately, there is a fairly simple solution, and it does not violate the "plugin realm" rules.

Introduction to TGM plug-in activation library

TGM Plugin Activation is a lightweight library designed to bundle themes with plugins. The idea is simple: when a user installs your theme, it lets the user install plugins from WordPress.org, an external website, or the theme’s folder. Here's how the library's creator, Thomas Griffin, defines this handy little tool:

TGM Plugin Activation is a PHP library that allows you to easily request or recommend plugins for your WordPress themes (and plugins). It allows your users to install and even automatically activate plugins in a single or batch manner using native WordPress classes, functions, and interfaces. You can reference prepackaged plugins, plugins from the WordPress plugin repository, or even plugins hosted elsewhere on the internet.

This is probably the smartest solution to the "plugin territory invasion" problem. And it’s easy to apply.

Let’s take a look!

Install TGM plug-in activation

Installing TGM plug-in activation is very simple. Just follow these steps:

  • Download the TGM plugin activation library from the Downloads section of the page.
  • Open the zip file and extract class-tgm-plugin-activation.php to your theme folder (anywhere you like).
  • Open the theme's functions.php file and use the require_once() function to request the class file (once) in the theme.
  • Create a function to configure TGM plugin activation and hook it to tgmpa_register via the add_action() function.
  • Finish!

It's so easy, you don't even need complex PHP code to request or recommend plugins. Take a look at the following code:

<?php

/**
 * Since I'm already doing a tutorial, I'm not going to include comments to
 * this code, but if you want, you can check out the "example.php" file
 * inside the ZIP you downloaded - it has a very detailed documentation.
 */

require_once dirname( __FILE__ ) . '/class-tgm-plugin-activation.php';

add_action( 'tgmpa_register', 'mytheme_require_plugins' );

function mytheme_require_plugins() {

    $plugins = array( /* The array to install plugins */ );
    $config = array( /* The array to configure TGM Plugin Activation */ );

    tgmpa( $plugins, $config );

}

?>
Copy after login

From now on, you can let users install new plugins by setting the $plugins variable in the function you just created.

Let's see how it's done.

Activate and install the plug-in through TGM plug-in

As can be seen from the above, the $plugins variable is an array. To define the plugins to install, you need to create an array within that array (so that you can set your own parameters). It sounds difficult, but it’s not:

<?php

$plugins = array(
	array( /* my first plugin */ ),
	array( /* my second plugin */ ),
	array( /* my third plugin */ ),
	// ...
	array( /* my nth plugin */ )
);

?>
Copy after login

There are several parameters available:

  • name(字符串,必需)- 插件的名称。
  • slug (字符串,必需)- 插件的 slug(通常是其文件夹的名称)。
  • required (布尔值,必需) - 如果设置为 true,您的主题将“需要”该插件。如果false,主题将“推荐”它。
  • source (字符串,有时需要)- 插件的源。如果是 WordPress.org 插件,则不应使用此参数;否则,这是必需的。
  • version (字符串,可选) - 插件所需的最低版本。例如;如果主题用户已经安装了所需的插件,但没有达到您指定的最低版本号,TGM 插件激活会警告用户进行更新。
  • force_activation (布尔值,可选) - 如果设置为 true,当您的主题处于活动状态时,用户将无法停用插件。有点烦人,但在某些情况下可能是必要的。
  • force_deactivation (布尔值,可选) - 如果设置为 true,一旦用户切换主题,插件将被停用。
  • external_url (字符串,可选) - 如果设置,插件的名称将链接到插件要求通知中的此地址。

您可以通过三个选项让您的用户通过 TGM 插件激活安装插件:您可以从 WordPress 插件目录、外部源(例如您自己的服务器或 CDN)或您的主题文件夹(例如/my-theme/plugins/shortcodes.zip)。

需要 WordPress.org 的插件

<?php

$plugins = array(
	array(
		'name'      => 'BuddyPress',
		'slug'      => 'buddypress',
		'required'  => false, // this plugin is recommended
	)
);

?>
Copy after login

从外部源请求插件

<?php

$plugins = array(
	array(
		'name'               => 'My Awesome Plugin',
		'slug'               => 'my-awesome-plugin',
		'source'             => 'http://files.my-website.com/my-awesome-plugin.zip',
		'required'           => true, // this plugin is required
		'external_url'       => 'http://my-website.com/introducing-my-awesome-plugin', // page of my plugin
		'force_deactivation' => true, // deactivate this plugin when the user switches to another theme
	)
);

?>
Copy after login

从主题目录中获取插件

<?php

$plugins = array(
	array(
		'name'               => 'My Super Sleek Slider',
		'slug'               => 'my-super-sleek-slider',
		'source'             => get_stylesheet_directory() . '/lib/plugins/my-super-sleek-slider.zip', // The "internal" source of the plugin.
		'required'           => true, // this plugin is required
		'version'            => '1.2', // the user must use version 1.2 (or higher) of this plugin
		'force_activation'   => false, // this plugin is going to stay activated unless the user switches to another theme
	)
);

?>
Copy after login

配置 TGM 插件激活

注意到示例代码末尾带有两个参数的 tgmpa() 函数了吗?第二个参数是 $config 变量,它也恰好是一个数组,就像 $plugins 参数一样。顾名思义,您可以使用此数组配置 TGM 插件激活库。它还有自己的一组选项需要设置:

  • id(字符串) - 您在主题中实现的 TGM 插件激活库的唯一 ID。这实际上非常重要:如果另一个插件也使用 TGM 插件激活,则不同的 ID 可以防止冲突。
  • default_path (string) - 主题内插件的默认绝对路径。设置此选项后,您可以使用 ZIP 文件的名称作为插件的 source 参数。
  • menu (字符串) - 插件安装页面的菜单项。
  • has_notices (boolean) - 如果设置为 true,则会显示必需/推荐插件的管理员通知。
  • dismissible (boolean) - 如果设置为 true,用户可以“忽略”通知。
  • dismiss_msg (string) - 如果 dismissable 选项设置为 false,则此消息将显示在管理通知上方。
  • is_automatic (boolean) - 如果设置为 true,插件将在用户同意安装后激活。
  • message (string) - 在插件表之前显示的可选 HTML。
  • strings (array) - 另一个 array 包含要显示的消息。您也可以将它们设置为可翻译字符串。查看 example.php 文件以查看消息字符串的完整列表。
<?php

$config = array(
	'id'           => 'mytheme-tgmpa', // your unique TGMPA ID
	'default_path' => get_stylesheet_directory() . '/lib/plugins/', // default absolute path
	'menu'         => 'mytheme-install-required-plugins', // menu slug
	'has_notices'  => true, // Show admin notices
	'dismissable'  => false, // the notices are NOT dismissable
	'dismiss_msg'  => 'I really, really need you to install these plugins, okay?', // this message will be output at top of nag
	'is_automatic' => true, // automatically activate plugins after installation
	'message'      => '<!--Hey there.-->', // message to output right before the plugins table
	'strings'      => array(); // The array of message strings that TGM Plugin Activation uses
);

?>
Copy after login

总结一切

正如您所看到的,通过 WordPress 主题提供功能并非不可能 - 您只需考虑用户从您的主题切换到另一个主题时的情况。 TGM 插件激活库提供了一种非常聪明的按书本操作的方法。

您觉得这个工具怎么样?您曾经使用过它,或者您打算将来使用它吗?请在下面发表评论,告诉我们您的想法。如果您喜欢这篇文章,请不要忘记与您的朋友分享!

The above is the detailed content of Leverage the power of the TGM plugin activation library in your theme. 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)

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

How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

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 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

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

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 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

How to Automate WordPress and Social Media with IFTTT (and more) How to Automate WordPress and Social Media with IFTTT (and more) Apr 18, 2025 am 11:27 AM

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

See all articles