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 therequire_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 theadd_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 ); } ?>
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 */ ) ); ?>
There are several parameters available:
-
name
(字符串,必需)- 插件的名稱。 -
slug
(字符串,必需)- 插件的 slug(通常是其文件夾的名稱)。 -
required
(布爾值,必需) - 如果設(shè)置為true
,您的主題將“需要”該插件。如果false
,主題將“推薦”它。 -
source
(字符串,有時需要)- 插件的源。如果是 WordPress.org 插件,則不應(yīng)使用此參數(shù);否則,這是必需的。 -
version
(字符串,可選) - 插件所需的最低版本。例如;如果主題用戶已經(jīng)安裝了所需的插件,但沒有達(dá)到您指定的最低版本號,TGM 插件激活會警告用戶進(jìn)行更新。 -
force_activation
(布爾值,可選) - 如果設(shè)置為true
,當(dāng)您的主題處于活動狀態(tài)時,用戶將無法停用插件。有點(diǎn)煩人,但在某些情況下可能是必要的。 -
force_deactivation
(布爾值,可選) - 如果設(shè)置為true
,一旦用戶切換主題,插件將被停用。 -
external_url
(字符串,可選) - 如果設(shè)置,插件的名稱將鏈接到插件要求通知中的此地址。
您可以通過三個選項(xiàng)讓您的用戶通過 TGM 插件激活安裝插件:您可以從 WordPress 插件目錄、外部源(例如您自己的服務(wù)器或 CDN)或您的主題文件夾(例如/my-theme/plugins/shortcodes.zip
)。
需要 WordPress.org 的插件
<?php $plugins = array( array( 'name' => 'BuddyPress', 'slug' => 'buddypress', 'required' => false, // this plugin is recommended ) ); ?>
從外部源請求插件
<?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 ) ); ?>
從主題目錄中獲取插件
<?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 ) ); ?>
配置 TGM 插件激活
注意到示例代碼末尾帶有兩個參數(shù)的 tgmpa()
函數(shù)了嗎?第二個參數(shù)是 $config
變量,它也恰好是一個數(shù)組,就像 $plugins
參數(shù)一樣。顧名思義,您可以使用此數(shù)組配置 TGM 插件激活庫。它還有自己的一組選項(xiàng)需要設(shè)置:
-
id
(字符串) - 您在主題中實(shí)現(xiàn)的 TGM 插件激活庫的唯一 ID。這實(shí)際上非常重要:如果另一個插件也使用 TGM 插件激活,則不同的 ID 可以防止沖突。 -
default_path
(string) - 主題內(nèi)插件的默認(rèn)絕對路徑。設(shè)置此選項(xiàng)后,您可以使用 ZIP 文件的名稱作為插件的source
參數(shù)。 -
menu
(字符串) - 插件安裝頁面的菜單項(xiàng)。 -
has_notices
(boolean) - 如果設(shè)置為true
,則會顯示必需/推薦插件的管理員通知。 -
dismissible
(boolean) - 如果設(shè)置為true
,用戶可以“忽略”通知。 -
dismiss_msg
(string) - 如果dismissable
選項(xiàng)設(shè)置為 false,則此消息將顯示在管理通知上方。 -
is_automatic
(boolean) - 如果設(shè)置為true
,插件將在用戶同意安裝后激活。 -
message
(string) - 在插件表之前顯示的可選 HTML。 -
strings
(array) - 另一個array
包含要顯示的消息。您也可以將它們設(shè)置為可翻譯字符串。查看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 ); ?>
總結(jié)一切
正如您所看到的,通過 WordPress 主題提供功能并非不可能 - 您只需考慮用戶從您的主題切換到另一個主題時的情況。 TGM 插件激活庫提供了一種非常聰明的按書本操作的方法。
您覺得這個工具怎么樣?您曾經(jīng)使用過它,或者您打算將來使用它嗎?請?jiān)谙旅姘l(fā)表評論,告訴我們您的想法。如果您喜歡這篇文章,請不要忘記與您的朋友分享!
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

The key to adding custom rewrite rules in WordPress is to use the add_rewrite_rule function and make sure the rules take effect correctly. 1. Use add_rewrite_rule to register the rule, the format is add_rewrite_rule($regex,$redirect,$after), where $regex is a regular expression matching URL, $redirect specifies the actual query, and $after controls the rule location; 2. Custom query variables need to be added through add_filter; 3. After modification, the fixed link settings must be refreshed; 4. It is recommended to place the rule in 'top' to avoid conflicts; 5. You can use the plug-in to view the current rule for convenience

robots.txt is crucial to the SEO of WordPress websites, and can guide search engines to crawl behavior, avoid duplicate content and improve efficiency. 1. Block system paths such as /wp-admin/ and /wp-includes/, but avoid accidentally blocking the /uploads/ directory; 2. Add Sitemap paths such as Sitemap: https://yourdomain.com/sitemap.xml to help search engines quickly discover site maps; 3. Limit /page/ and URLs with parameters to reduce crawler waste, but be careful not to block important archive pages; 4. Avoid common mistakes such as accidentally blocking the entire site, cache plug-in affecting updates, and ignoring the matching of mobile terminals and subdomains.

1. Use performance analysis plug-in to quickly locate problems. For example, QueryMonitor can view the number of database queries and PHP errors, BlackboxProfiler generates function execution reports, and NewRelic provides server-level analysis; 2. Analyzing PHP execution performance requires checking time-consuming functions, debugging tools usage and memory allocation, such as Xdebug generates flame graphs to assist in optimization; 3. Monitor database query efficiency can be checked through slow query logs and index checks, QueryMonitor can list all SQL and sort by time; 4. Combining external tools such as GooglePageSpeedInsights, GTmetrix and WebPageTest to evaluate front-end plus

WordPressrequiresatleastPHP7.4,thoughusing8.0orhigherisrecommendedforbetterperformanceandsecurity.Olderversionslike5.6areoutdated,unsupported,andposesecurityrisks.UsingupdatedPHPimprovessecurity,enhancesperformance,andensurescompatibilitywithmodernpl

InspectorControls is a component used in Gutenberg development to add custom controls in the right sidebar. 1. It belongs to the @wordpress/block-editor package. 2. It is often used with PanelBody, TextControl and other components. 3. When using it, you need to introduce and reasonably lay out control types such as text boxes, pull-down selections, switches, sliders and color selectors in edit.js. 4. Pay attention to grouping settings, keep them simple, support internationalization and optimize performance.
