An old WP bug

I’m testing on WordPress version 4.3.3. I know it’s out of date but my excuse is that I want at least some backwards compatibility. I’ll check this on an up-to-date version later.

I was trying to use the function current_user_can() to control access to a dashboard widget in a plugin that I’m writing, but the script kept crashing. I checked the syntax — no problem — and then checked that the function existed using the PHP function function_exists() — again, no problem. But when I commented out the function the script worked!

I checked the error log, where I found the line:

PHP Fatal error:  Call to undefined function wp_get_current_user() in /.../wp-includes/capabilities.php on line 1441

and a stack-trace showing that wp_get_current_user() is called by current_user_can(). Clearly if wp_get_current_user() is undefined that would explain the problem, by why is it undefined? It’s part of WordPress core after all!

After a bit of Googling (or Binging, to be more accurate) I found a thread on the WordPress support forum that related this to a WordPress bug. Apparently the capabilities.php file should ‘include’ pluggable.php but doesn’t, and consequently the wp_get_current_user() function isn’t loaded when it’s called as a result of my call on current_user_can(). (I must admit I’m not altogether clear how a function that hasn’t been loaded can return a true response to the file_exists() function, but that’s for another day.)

What is surprising though is that the thread on the forum is five years old and it’s still unresolved, although all it takes is one extra line:

require_once('pluggable.php'); // line to be added

at the top of capabilities.php! The version referred to in the thread is 3.0.1.

Perhaps it’s been fixed in version 4.5 — I’ll check. Anyway, if you hit this problem you know what to do. Add the extra line to capabilities.php, bearing in mind that until it’s fixed at source, every time you upgrade WordPress it will break again, and you’ll have to add the line to the new version as well. Not the end of the world, but a nuisance!