WordPress – current_user_can in functions.php

So I am trying to run a simple if statement inside the wp-functions.php file and am using current_user_can. However I get PHP errors like: “Fatal error: Call to undefined function current_user_can() in…”

If anyone could take a look at my code, that would be much appreciated.

Read More

The code I am using is here:

        global $current_user_can;
        if ( current_user_can( 'manage_options' ) ) {
            /* Admin User */

        } else {
            /* Member */
            echo "<p>something</p>"; 
}  

Related posts

3 comments

  1. This usually happens because pluggable.php is not loaded by some reason. Try to add this before your function;

    if(!function_exists('wp_get_current_user')) { include(ABSPATH . "wp-includes/pluggable.php"); }
    

    It just checks if pluggable is loaded, and if not, it includes it.

  2. if you want to check directly the role of the member, you can use this code:

    global $current_user;
    get_currentuserinfo();
    
    if( !in_array( 'administrator', $current_user->roles ) ) {
     //Do something
    } else {
     //Do something else
    }
    
  3. if you are creating a plugin, you must have to include like

    if(!function_exists('wp_get_current_user')) { include(ABSPATH . "wp-includes/pluggable.php"); }// no need to add for theme functions
    global $current_user_can;
        if ( ! current_user_can( 'manage_options' ) ) {
            // your stuff here
    } 

Comments are closed.