Access WordPress variables in JavaScript

Hey guys. Today I will teach you how to access any WordPress variable in JavaScript with some custom PHP snippet code. If you recently started to develop WordPress plugins surely you came across problems. To be more specific, maybe you wanted to access WordPress variables in JavaScript. Well, good news! I’m here to help.

Bellow it’s the code that gives you the opportunity to access WordPress variables in JavaScript like a boss! Please take in mind that this can be accomplished using the “wp_localize_script” function that WordPress made available. To be more specific this functions is typically used for localizing stings. More details on this function can be found here. This can also be used to assign WordPress data to different Javascript variables that will be available inside the Javascript handle used in the wp_enqueue_script function.

To make an example I will use the “admin_print_scripts” action which will only run in the admin section of course. You can change this as you want based on your needs.


Ok, hope it’s clear so far. We now must define the “adminAddScripts” function that will be called from the snippet above. Please take a good look at the use of “wp_localize_script” function and how I use it to assign WordPress variables in JavaScript. The first parameter refers to the handle of your JavaScript file loaded in “wp_enqueue_script”. The second one refers to the JavaScript Object that will be used to reference these variables. The third one is the array of the variable definitions.

Access WordPress variables in JavaScript function

 $pluginUrl,
	    'dataPerPage' => $dataPerPage
	    )
    );
}
?>

The last part is the most simple one. How to gain access to your WordPress variables in Javascript. You can get them in the fallowing manner.

alert(jsFileVariables.dataPerPage);
alert(jsFileVariables.pluginUrl);

Ok guys. This is it. Hope it helps you as much as it helped me.

Related Posts

PHP fundamentals – introduction, php instructions and variables

Let users find links on your page by typing

Web-scraping framework written in Javascript

JavaScript Notifications For Bootstrap Or jQuery UI

Leave a Reply