问题描述
我正在完全从头开始创建我的第一个插件。每当我尝试将命名空间添加到“template-plugin-activate.PHP”文件时,我都会收到以下错误:
Plugin Could not be activated because it triggered a Fatal error.
Fatal error: Uncaught TypeError: call_user_func_array(): Argument #1 ($function) must be a valid callback,class "TemplatePluginActivate" not found in C:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.PHP:292 Stack trace: #0 C:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.PHP(316): WP_Hook->apply_filters('',Array) #1 C:\xampp\htdocs\wordpress\wp-includes\plugin.PHP(484): WP_Hook->do_action(Array) #2 C:\xampp\htdocs\wordpress\wp-admin\plugins.PHP(193): do_action('activate_templa...') #3 {main} thrown in C:\xampp\htdocs\wordpress\wp-includes\class-wp-hook.PHP on line 292
下面是我的文件。任何帮助表示赞赏。
// inc/template-plugin.PHP
<?PHP
namespace Inc;
class TemplatePluginActivate
{
public static function activate() {
flush_rewrite_rules();
}
}
defined( 'ABSPATH' ) or die( 'You can\t access this file.' );
if ( file_exists( dirname( __FILE__ ) . '/vendor/autoload.PHP' ) ) {
require_once dirname( __FILE__ ) . '/vendor/autoload.PHP';
}
use Inc\TemplatePluginActivate;
if ( !class_exists( 'TemplatePlugin' ) ) {
class TemplatePlugin
{
//
}
}
require_once plugin_dir_path( __FILE__ ) . 'inc/template-plugin-activate.PHP';
register_activation_hook( __FILE__,array( 'TemplatePluginActivate','activate' ) );
require_once plugin_dir_path( __FILE__ ) . 'inc/template-plugin-deactivate.PHP';
register_activation_hook( __FILE__,array( 'TemplatePluginDeactivate','deactivate' ) );
// composer.json
{
"name": "author/template-plugin","description": "awesome starter plugin example","type": "project","license": "GPL","authors": [
{
"name": "author","email": ""
}
],"minimum-stability": "dev","require": {},"autoload": {
"psr-4": {"Inc\\": "./inc"}
}
}
解决方法
问题在于 register_activation_hook()
。
您的回调是 activate()
类的 TemplatePluginActivate
方法。一旦引入命名空间,就需要更新。类将是 Inc\TemplatePluginActivate
。
register_activation_hook( __FILE__,array( 'Inc\TemplatePluginActivate','activate' ) );
此外,您的停用操作也在激活时运行。您需要的钩子是 register_deactivation_hook()
。