I want to execute custom jquery code which shows login dialog to user if he clicks a button and he is not logged in. How could I do that?
9 Answers
In case you want to know if the user is logged in at the current moment, try this. The other answers check if the user is logged in or not when the page loaded, not the time when you're running the javascript. The user could have logged in in a separate tab, for instance.
Put this in your javascript
var data = {
action: 'is_user_logged_in'
};
jQuery.post(ajaxurl, data, function(response) {
if(response == 'yes') {
// user is logged in, do your stuff here
} else {
// user is not logged in, show login form here
}
});
Put this in your functions.php
function ajax_check_user_logged_in() {
echo is_user_logged_in()?'yes':'no';
die();
}
add_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in');
add_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in');
-
1
-
1wordpress sets it to 'yoursite.com/wp-admin/admin-ajax.php'. That's the url on which all the ajax requests are supposed to be sent Commented Oct 24, 2012 at 19:25
-
I put the jQuery.post inside jquery click handler but this doesn't work. do you have any idea how to solve it? Commented Oct 24, 2012 at 19:28
-
1[codex](codex.wordpress.org/AJAX_in_Plugins) said that in latest wordpress versions this is already defined. Maybe you can define your own version of ajaxurl with wp_localize_script Commented Oct 24, 2012 at 19:45
-
1Incase anyone get the ajaxurl is not defined... stackoverflow.com/questions/17710728/…– DanielCommented Feb 3, 2015 at 22:09
Check the class
attribute for body
: If the theme is using body_class()
the body has a class named logged-in
for users that are logged in. Be aware the function can be used on the element html
too.
Example with jQuery:
if(jQuery('body').hasClass('logged-in')){
// Do something
}
Example with pure JavaScript:
if (document.body.classList.contains('logged-in')) {
// do something
}
You can also just use is_user_logged_in()
as a condition to enqueue or print the script.
-
-
I like the idea of just checking the body for
logged-in
class. Just have to be sure that themes usebody_class();
orget_body_class();
Otherwise, that's not a super reliable solution. Although, I use those functions in my themes, so that's a good solution for me. Thanks for the simple idea. Commented Feb 16, 2017 at 17:22
Please add body_class() to your html body
<body <?php body_class(); ?>>
//your html code
</body>
This will add logged-in
for logged user then you can use following jquery code to execute your custom juqery code only for logged user.
if ($('body').hasClass('logged-in')) {
//execute your jquery code.
}
-
I dunno why this one was down voted. Approach is fully valid. +1– kaiserCommented Dec 31, 2013 at 11:54
-
I dont know. I have same question. Answer is valid but why down vote. Commented Jan 22, 2014 at 4:42
-
Hm. Maybe because it uses jQuery instead of the right way (using a filter and the callback). Some people are allergic to jQuery.– kaiserCommented Jan 22, 2014 at 14:28
-
1good, but it wouldnt tell actual login state if you use a cacheing plugin with page cache enabled. Commented Mar 19, 2018 at 7:29
Please note that none of the above examples are reliable in case you use a page cacheing plugin, then the code in body tag will be static. Also there is a simple way to do this (with no extra query to ajax which is not optimal)
If you want to test user logged in state with javascript, you can use this code to set cookie when user logged in and delete cookie when user logged out. Add this eg. to your theme functions.php
function login_function() {
setcookie('wp_user_logged_in', 1, time() + 31556926, '/');
$_COOKIE['wp_user_logged_in'] = 1;
}
add_action('wp_login', 'login_function');
function logout_function() {
unset($_COOKIE['wp_user_logged_in']);
setcookie('wp_user_logged_in', null, -1, '/');
}
add_action('wp_logout', 'logout_function');
Then its a simple test of cookie in javascript.
if (document.cookie.indexOf('wp_user_logged_in') !== -1) {
//do something when user logged in
} else {
//do something when user logged out
}
-
1This is indeed pretty simple, reliable and in worst case executes almost instantly after page load (if loading script in footer without render blocking) unlike other answers. Ajax is slow and relying on body classes will fail on caching. Need to add this cookie to Cookie Policy text. Thank You Janos. Commented Apr 19, 2019 at 0:13
-
As a follow-up, there is a problem with synchronization of default WordPress cookies and newly created script-accessible cookie, but I've received a great and simple answer on how to solve it: stackoverflow.com/questions/56208574/… Commented May 27, 2019 at 3:58
Another example, in case you want to use it for AJAX calls.
// Simplified... please note, that all names/vars/etc. in my class got unique names.
// ...the same goes for the script handler.
class wpse69814_example
{
public $response;
public function __construct()
{
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'localize' ), 20 );
}
public function enqueue()
{
wp_enqueue_script(
'wpse69814_handler',
plugins_url( 'url/to/file.js', __FILE__ ),
array( 'jquery' ),
filemtime( plugins_dir_path( __FILE__ ).'/path/to/file.js' ),
true
);
}
public function localize()
{
wp_localize_script( 'wpse69814_handler, 'wpse69814_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce( 'wpse69814_nonce' ),
'action' => 'wpse69814-handler-action',
'data' => array(
'is_user_logged_in' => is_user_logged_in(),
)
)
}
}
-
-
-
Since the CDN doesn't authenticate with WordPress,
is_user_logged_in
will be cached as false in the DOM when origin is hit User state should be abstracted out to a no-cache thread via XHR when using a CDN. @Mridul Aggarwal's approach works but with no-cache headers in the response. Commented Dec 31, 2013 at 5:42 -
@BrianFegter Good catch. Fixed that... I think. Upvoted other answers as well.– kaiserCommented Dec 31, 2013 at 11:54
Thanks to this post and another post, I found a solution to my issue. I'm just posting in case anyone might find it useful.
Works on current WordPress sites
This code checks if user is logged or not using jquery. If the user is NOT logged in, it prevents the user from right clicking content and copying images and text.
$(document).ready(function(){
// if user is not logged in...
if (!document.querySelector('body.logged-in')){
//lock all content
disableSelection(document.body);
// disable image click
$('img').bind('contextmenu', function(e){return false;});
console.log('hello');
}
// function to lock all content
function disableSelection(target){
$(function() {
$(this).bind("contextmenu", function(e) {
e.preventDefault();
});
});
if (typeof target.onselectstart!="undefined") //For IE
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
target.style.MozUserSelect="none"
else //All other route (For Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default";
}
})
I am using an alternative way without ajaxurl
and body class
. I just don't trust the body class, that might not exist in all of the themes.
In functions.php
you should have:
add_action( 'wp_body_open', 'custom_body_open' );
function custom_body_open() {
$logged_in = is_user_logged_in() ? 'yes' : 'no'; //WP function to check if user is logged in or not
echo '<div style="display:none" class="user_is_logged_in" data-logged-in="' . $logged_in . '" ></div>';
}
That creates an invisible div
at the start of body tag with:
- class name "user_is_logged_in" - only for jQuery reference.
- style "display: none" - makes div invisible. Instead you can use CSS:
.user_is_logged_in { display: none }
- "data-(logged-in)" value "yes" (logged in) or "no" (not logged in). That value will later be asked with
jQuery
.
In jQuery I ask the "data-logged-in" value and then act accordingly:
jQuery(document).ready(function($) {
var logged_in = $(".user_is_logged_in").data("logged-in") == 'yes' ? true : false;
if (logged_in) {
...
}
else {
...
}
}
Here is the WordPress script that will add class into the Body tag if the user is login or not login
https://gist.github.com/raftaar1191/55fe297db0724e62883846b3ed31b543
I appreciated all the answers but localize script or checking the css class would be, in my opinion, not the best practice as the css class checking is not 100% reliable and the localize script function is, as the name suggests, localising.
After Wordpress 4.5 the best solution would be adding an inline script as follows:
<?php
function detect_login() {
$isLoggedIn = is_user_logged_in();
wp_register_script( 'detect_login', '' );
wp_enqueue_script( 'detect_login');
wp_add_inline_script( 'detect_login', "var isLoggedIn = $isLoggedIn" );
}
add_action( 'wp_enqueue_scripts', 'detect_login' );
And then obviously check the global scope which is now sadly polluted by our global var isLoggedIn as follows: window.isLoggedIn
-
-
@JacobPeattie Yes, the reason why they created
wp_add_inline_script()
is to avoid people using the localize script function to declare global variables. As the name suggests this is a better fit, why using something else which in the beginning wasn't intended for that purpose if we have a good alternative? Commented Feb 17, 2020 at 9:24 -
That's not what it was added for. It was added to support adding small bits of executable code before or after a script, to support things like font loaders. make.wordpress.org/core/2016/03/08/… Commented Feb 17, 2020 at 9:28
-
@JacobPeattie exactly, and what was
wp_localize_script()
string added for? Polluting the global scope with global variables? Or to actually localize as the name suggests? Commented Feb 17, 2020 at 10:06 -
What are you talking about? wp_localize_script forces you to namespace your variables inside an object. Your own answer is adding a variable to the global scope without any sort of namespace. Commented Feb 17, 2020 at 10:27