如何在插件激活回调中更新全局变量?

时间:2021-04-20 作者:T Nguyen

对不起,我是个笨蛋。我相信这对大多数人来说都是一个简单的问题。我正在尝试为我的插件注册激活和停用挂钩。在里面the docs, 它们警告激活回调无法访问全局变量:

如果您使用的是全局变量,您可能会发现传递给register\\u activation\\u hook()的函数在调用时无法访问全局变量,即使您在函数中这样声明它们的全局范围:

。。。

因此,主体变量在activate_plugin() 函数和不是全局的,除非明确声明其全局范围:

global $myvar;
$myvar = \'whatever\';

function myplugin_activate() {

   global $myvar;
   echo $myvar; // this will be \'whatever\'
}
register_activation_hook( __FILE__, \'myplugin_activate\' );

因此,根据这个建议,我将代码设置为:

global $post_id;
$post_id = 0;

function install_xxx() {
    global $post_id;

    $post = array(
        \'post_title\'    => __( \'Thank You\', \'xxx\' ),
        \'post_content\'  => __( \'Lorem ipsum dolor.\', \'xxx\' ),
        \'post_status\'   => \'publish\',
        \'post_name\'     => \'thank-you\',
        \'post_type\'     => \'page\'
    );

    $post_id = wp_insert_post( $post, true );
    error_log(\'Inserted page: \' . $post_id);
}

function uninstall_xxx() {
    global $post_id;
    error_log(\'Removing page: \' . $post_id);
    $post = wp_delete_post( $post_id, true );
}

register_activation_hook( __FILE__, \'install_xxx\' );
register_deactivation_hook( __FILE__, \'uninstall_xxx\' );

但在我的日志中,它会回应如下内容:

插入的页面:109删除页面:0,当然,页面不会被删除。

换句话说,全球$post_id 未更新。知道我做错了什么吗?

1 个回复
SO网友:T Nguyen

多亏了@Tom J Nowell的帮助,我修复了代码,将创建的页面ID持久化为选项:

function install_xxx() {    
    $post = array(
        \'post_title\'    => __( \'Thank You\', \'xxx\' ),
        \'post_content\'  => __( \'Lorem ipsum dolor.\', \'xxx\' ),
        \'post_status\'   => \'publish\',
        \'post_name\'     => \'thank-you\',
        \'post_type\'     => \'page\'
    );

    $post_id = wp_insert_post( $post, true );
    add_option( \'xxx_thankyou_page_id\', $post_id );
    error_log(\'Inserted page: \' . $post_id);
}

function uninstall_xxx() {
    $post_id = get_option( \'xxx_thankyou_page_id\' );
    error_log(\'Removing page: \' . $post_id);
    if ( $page_id ) {
        $post = wp_delete_post( $post_id, true );
    }
}

register_activation_hook( __FILE__, \'install_xxx\' );
register_deactivation_hook( __FILE__, \'uninstall_xxx\' );

相关推荐

OOP development and hooks

我目前正在为Wordpress编写我的第一个OOP插件。为了帮助我找到一点结构,a boiler plate 这为我奠定了基础。在里面Main.php 有一种方法可以为管理员加载JS和CSS资产:/** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 0.1.0 * @access private