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?
Leave a Reply
You must be logged in to post a comment.
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?
You must be logged in to post a comment.
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
Put this in your
functions.php
Check the
class
attribute forbody
: If the theme is usingbody_class()
the body has a class namedlogged-in
for users that are logged in. Be aware the function can be used on the elementhtml
too.Example with jQuery:
Example with pure JavaScript:
You can also just use
is_user_logged_in()
as a condition to enqueue or print the script.Please add body_class() to your html 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.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
Then its a simple test of cookie in javascript.
Another example, in case you want to use it for AJAX calls.
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.
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:
And then obviously check the global scope which is now sadly polluted by our global var isLoggedIn as follows:
window.isLoggedIn