Solution:2
These are two of the most popular web languages
The WordPress core code is written in PHP and the Admin Dashboard interface makes heavy use of jQuery and JavaScript.
Of course these are all different programming languages and as you would expect, there’s no reason for them to work together at a development level.
This is called scope.
Scope defines the boundary where your data and variables will work in and there’s different levels of scope even within the same programming language. We’re not going there.
As separate languages, PHP, jQuery and JavaScript are entirely out of scope.
Their code runs through different interpreters build into the server for PHP and the web browser for jQuery and JavaScript.
They don’t even acknowledge each others presence.
But as all three are used heavily in developing WordPress websites, there’s going to be occasions where you just need to pass WordPress data from PHP into your jQuery and JavaScript files so that they can do something cool in the user interface (UI) that can’t be done with PHP (easily).
Here’s how to do just that.
Passing Variables Between Languages
We’re going to show just how easy it is to grab information from the WordPress site using PHP, bundle that up and display it in the front end UI using jQquery or JavaScript.
First we create our test jQuery script file called lc-jquery.js. I keep this in a js folder inside our current theme.
Pretty simple stuff here.
We’re detecting a click on a link and displaying an alert box showing the undefined variable lc_jqpost_info.
Hang on – where did lc_jqpost_info come from?
Patience my young padawan.
We’ve created a test page on WordPress and added the following link on it with the #clickme ID so that we can hook our jQuery code to it.
<a id=”clickme” href=”#”>Show me stuff</a>
Now we need to load jQuery the script into WordPress and the proper way of doing that is using the wp_enqueue_script() function.
Copy the following code into your functions.php file.
You’ll need to adjust the location for your script file if you haven’t placed it in the same place as this example.
If you reload your test page and click on the link you’ll find, in the inspect element window of the Chrome debugger, that there’s a jQuery error as the script can’t find the variable lc_jqpost_info.