![](/img/trans.png)
[英]Wordpress: register_activation_hook doesnt' working on my plugin
[英]plugin activation hook not working in wordpress
我正在尝试开发我的第一个Wordpress插件,并且我在第一阶段就陷入了困境。 我正在尝试在插件激活时设置一些选项和数据库表,但没有运气。 无论我做什么,插件都会激活,但数据库不受影响且选项不存储在DB中。 我尝试在构造函数中回显,但似乎它永远不会到达它。 我在WP中激活了调试,但没有报告错误。 该功能没有被挂钩。 有人能发现我的代码有什么问题吗?
在此先感谢您的帮助。
class Myplugin {
private static $instance;
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
register_activation_hook( __FILE__, array( &$this, 'plugin_activate' ) );
}
public function plugin_activate() {
if ( version_compare( get_bloginfo( 'version' ), '3.8.2', ' < ' ) ) {
deactivate_plugins( basename( __FILE__ ) );
} else {
$rlm_rsvplus_options = array(
'db_version' => '1.0',
'event_name' => '',
'end_date' => '',
);
update_option( 'rlm_myplugin_options', $rlm_myplugin_options );
require_once( "includes/rlm_myplugin_db_setup.php" );//It never reaches this file.
}
}
}
$myplugin = Myplugin::get_instance();
register_activation_hook
调用需要在类本身之外。
就像是:
class Myplugin {
private static $instance;
public static function get_instance() {
if ( ! self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// do other stuff here
}
public function plugin_activate() {
if ( version_compare( get_bloginfo( 'version' ), '3.8.2', ' < ' ) ) {
deactivate_plugins( basename( __FILE__ ) );
} else {
$rlm_rsvplus_options = array(
'db_version' => '1.0',
'event_name' => '',
'end_date' => '',
);
update_option( 'rlm_myplugin_options', $rlm_myplugin_options );
require_once( "includes/rlm_myplugin_db_setup.php" );
}
}
register_activation_hook( __FILE__, array( 'Myplugin', 'plugin_activate' ) );
您可以阅读Francis Yaconiello关于如何编写WordPress插件的以下教程的更多内容。
<?php register_activation_hook( $file, $function ); ?>
$文件
(字符串)(必需) wp-content / plugins目录中主插件文件的路径 。 完整路径将起作用。 默认值:无
$函数
(callback)(必需)激活插件时要运行的函数。 任何PHP的回调伪类型都可以。 默认值:无
如果从主插件文件之外的文件调用函数,则挂钩将不起作用,因为它没有指向正确的文件。 FILE将指向编写代码的文件。 因此,如果您碰巧从其他地方(另一个文件 - 而不是主插件文件) 包含这部分代码,除非您指出正确的路径,否则它不应该工作。
解决方案可能是在主插件文件中声明一个常量。
your_main_plugin_file.php
define(PLUGIN_FILE_URL, __FILE__);
然后在包含的文件中使用它,就像这样。
包括/ some_file.php
<?php register_activation_hook( PLUGIN_FILE_URL, ['your_class_name_here', 'your_class_method_name_here']); ?>
或者如果你使用函数而不是类,那么就做
<?php register_activation_hook( PLUGIN_FILE_URL, 'your_function_name_here'); ?>
为了工作register_activation_hook或者register_deactivation_hook ,函数应该在索引文件中,或者我们需要指定文件参数的完整路径。
替换这个:
register_activation_hook( FILE, array( &$this, 'plugin_activate' ) );
附:
register_activation_hook( FILE . 'plugin-main-file.php', array( &$this, 'plugin_activate' ) );
这里的重点是register_activation_hook($ file,$ function);
这里$ file表示主插件文件的路径
参考: https : //codex.wordpress.org/Function_Reference/register_activation_hook
谢谢, - 阿迪
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.