检查用户权限在插件中是否有效,但在管理面板中产生错误


Check user permissions works in plugin but produce error in admin panel

我写了一个小插件,用于检查用户权限并将相应的JSON发送到ExtJS客户端。

<?php
/*
Plugin Name: Check gallery user
Description: Check gallery user
Version: 1.0
*/
if (strpos(__FILE__, 'check_manage_options.php') !== false) {
    require('../../../wp-load.php');
    $manage_options = 'no';
    if (is_user_logged_in() && current_user_can('manage_options')) {
        $manage_options = 'yes';
    }
    $perms = array("perms" => array("perm" => $manage_options));
    echo json_encode($perms);
}
?>

使用ExtJS,它可以正常工作。但是当我尝试进入"/wordpress/wp-admin/"URL时,我遇到了错误:

警告:要求(../../../wp-load.php) [function.require]: 未能 打开流:没有这样的文件或目录 Z:''home''localhost''www''wordpress''wp-content''plugins''CheckGalleryUser''check_manage_options.php 在第 9 行

致命错误:require() [function.require]:需要打开失败 '../../../wp-load.php' (include_path='.;/usr/local/php5/PEAR') in Z:''home''localhost''www''wordpress''wp-content''plugins''CheckGalleryUser''check_manage_options.php 在第 9 行

我也尝试了另一种方法:

<?php
/*
Plugin Name: Check gallery user
Description: Check gallery user
Version: 1.0
*/
add_action('init', 'check_gallery_user');
function check_gallery_user() {
$manage_options = 'no';
if (is_user_logged_in() && current_user_can('manage_options')) {
    $manage_options = 'yes';
}
}
$perms = array("perms" => array("perm" => $manage_options));
echo json_encode($perms);
?>

然后我得到这样的错误:

致命错误:调用未定义的函数 add_action() Z:''home''localhost''www''wordpress''wp-content''plugins''CheckGalleryUser''check_manage_options.php 在第 7 行

请尝试以下方法

<?php
/*
Plugin Name: Check gallery user
Description: Check gallery user
Version: 1.0
*/
function cgu_init() {
    if ( isset( $_GET['cgu_check'] ) && 'check' === $_GET['cgu_check'] ) {
        $manage_options = 'no';
        if ( is_user_logged_in() && current_user_can( 'manage_options' ) ) {
            $manage_options = 'yes';
        }
        $perms = array( "perms" => array( "perm" => $manage_options ) );
        echo json_encode( $perms );
        die();
    }
}
add_action( 'init', 'cgu_init' );

然后,当您发送请求时,只需将其发送给http://your-site/?cgu_check=check

问题

解决了!

<?php
/*
Plugin Name: Check gallery user
Description: Check gallery user
Version: 1.0
*/
if ( isset( $_GET['cgu_check'] ) && 'check' === $_GET['cgu_check'] ) {
    require('../../../wp-load.php');
    $manage_options = 'no';
    if (is_user_logged_in() && current_user_can('manage_options')) {
        $manage_options = 'yes';
    }
    $perms = array("perms" => array("perm" => $manage_options));
    echo json_encode($perms);
}
?>

此外,我在 php 中设置了 output_buffering = On.ini因为此代码在"/wordpress/wp-admin/"URL 上导致"警告:无法修改标头信息 - 标头已发送"警告。谢谢!