如何检查当前是否在 Wordpress Admin 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4128273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:40:27  来源:igfitidea点击:

How to check if currently in Wordpress Admin?

wordpress-pluginadminwordpress

提问by Matt

I am creating my first plugin and have a single function that controls the output. This function has different output based on whether or not it is being viewed from within the WordPress admin vs. the frontend. Is there any way to easily test whether or not my function is being triggered from within admin vs the frontend?

我正在创建我的第一个插件并有一个控制输出的功能。根据是否从 WordPress 管理员和前端查看它,此函数具有不同的输出。有什么方法可以轻松测试我的功能是否是从管理员内部还是前端触发的?

I've tried conditionally checking the query string against the name of my plugin "page" name but it seems to fail on some servers/installs.

我已经尝试根据我的插件“页面”名称的名称有条件地检查查询字符串,但它似乎在某些服务器/安装上失败。

Thanks

谢谢

回答by Matt

Duh, this was too obvious. For some reason I was thinking this had to do with an admin user. if(is_admin()) { ...output my admin stuff....}

呃,这太明显了。出于某种原因,我认为这与管理员用户有关。 if(is_admin()) { ...output my admin stuff....}

http://codex.wordpress.org/Function_Reference/is_admin

http://codex.wordpress.org/Function_Reference/is_admin

回答by psycho brm

If you want to know whether current user IS ADMIN, then you should use this:

如果你想知道当前用户是否是 ADMIN,那么你应该使用这个:

   $is_admin = current_user_can( 'manage_options' );

I got misguided by the above answer, so a little note to keep others from making the same mistake.

我被上面的答案误导了,所以请注意一点,以防止其他人犯同样的错误。

回答by Charles Jaimet

Note that is_admin()only works in the backend. For any part of the plugin that shows on the public website you need to use current_user_can().

请注意,is_admin()仅适用于后端。对于在公共网站上显示的插件的任何部分,您需要使用current_user_can().

if ( current_user_can( 'administrator' ) ) {
  // your code goes here
}

回答by theRunner

See is_admin_request()for a working solution.

有关有效解决方案,请参阅is_admin_request()

回答by Gaurab paul

<?php 
global $current_user;
get_currentuserinfo();
$user_id = $current_user->ID

//usually admin user id is 1 if its not working check admin user id from wp_users table
if($user_id == 1) {
   //write your stuff
}
?>