Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress: Fatal error: Call to undefined function is_user_logged_in()

Tags:

php

wordpress

I'm loading a PHP script in a wordpress page but when the script is run I get this:

Fatal error: Call to undefined function is_user_logged_in()

Code that it tries to run:

<?php
if ( is_user_logged_in() == true ) {
  /* Some code */
} else {
 /* Some other code */
}
?>

I tried searching for an answer but I couldn't find a working solution.
From what I found on the internet my script is running outside of wordpress and that's why it can't find the function.

like image 344
Android4682 Avatar asked Jan 08 '23 20:01

Android4682


1 Answers

Perhaps you are running the code too early as mentioned here: https://wordpress.org/support/topic/fatal-error-call-to-undefined-function-is_user_logged_in

The problem is that is_user_logged_in is a pluggable function, and is therefore loaded after this plugin logic is called. The solution is to make sure that you don't call this too early.

His solution was to wrap the code in another function which is called on init and can be put in your functions.php file:

function your_login_function()
{
    if ( is_user_logged_in() == true ) {
       /* Some code */
    } else {
        /* Some other code */
    }
}
add_action('init', 'your_login_function');
like image 53
Tyler Avatar answered Jan 10 '23 10:01

Tyler