Use "ajaxurl" in js file

wordpress
tips-and-tricks

#1

Hello everybody!

I make wp theme. I need to know in the js file, if the admin part of the site is open. Is it possible to use this global variable “ajaxurl” for it?

Example:

if (typeof ajaxurl === "undefined") {
    console.log ( "You are in frontend of site");
}
else {
    console.log ( "You are in backendof site");
}

#2

Are you asking if you can access ajaxurl on both the frontend and admin area?


#3

I would just check if body.hasClass(‘wp-admin’)


#4

Thanks for answer. No I read that “ajaxurl” exist only in admin part and I think to use it for test:
-if "ajaxurl " exist - it mean that it is admin part of site
-if "ajaxurl " not exist - it mean that it is frontend of site


#5

I read that “ajaxurl” exist only in admin

This is correct but it’s common for other plugins to load it on the frontend so this is not going to be a reliable check for you. @tommusrhodus has a great suggestion.


#6

Thanks, I will read about “.hasClass(‘wp-admin’)” more now