I am creating a plugin and wish to check if the user is logged in the run another function.
This is my first ever plugin and i am still learning how to program at the same time. following I have a simple user conditional, if user is logged in and i am also retrieving data from an array to check if the admin has checked Yes in the plugin options to check for user logged in then execute another function. however I am getting an error Call to undefined function is_user_logged_in()
i think i may need to wrap my conditional in a function and then add an action, can someone please help me. thanks
/* Logged user conditionals */
$logged = get_option('lu_ban_data');
if ($logged['loggedU'] == 'loggedYes' && is_user_logged_in() ) {
lu_ban_detect();
} else {
return false;
}
update
Okay I think i managed to get it to work
add_action( 'init', 'lu_user_logged' );
function lu_user_logged() {
$logged = get_option('lu_ban_data');
echo $logged;
if ($logged['loggedU'] == 'loggedYes' && is_user_logged_in() ) {
lu_ban_detect();
} else {
return false;
}
}
is this the proper way?
The point of the code is to load the
lu_ban_detect
in the footer of the page. That function then prints Javascript to the footer, per this comment:That being the case, this is not the proper way to do this. Printing scripts directly to the page is discouraged, and the code looks overcomplicated to me.
The first change I’d make would be this:
You are printing in the footer, so just hook to
wp_footer
, and there is no need toreturn
anything as far as I can tell. I also putis_user_logged_in()
first because you might save a query that way.But, as mentioned, you should probably not be echoing scripts directly into the page.
You can
echo
data into the page like this:The first parameter to
wp_localize_script
needs to be a script that is already enqueued.If you need to load more complicated Javascript, you should probably register and enqueue a
.js
file.