Passing a php variable to jQuery OR Why I insist on making everything harder than it needs to be, Pt. 1

This took me 2 days to crack, and it should’ve only taken me an hour. This could also be filed under “How to use SimpleWeather.js with WordPress.”

Currently, I’m working on a project where I’m using WordPress to show a series of travel products, each with unique content like destination cities, product descriptions, price, and more.

The products are presented in a carousel, and when a user clicks on the ‘Learn More’ button, they’ll see a modal with additional information, photos, and location specific data; specifically, I wanted to have the weather show up for each destination city.


Products post type is queried to create a carousel of hotels, or resorts, or whatever.


A modal opens with details about this product, including a custom weather forecast, based on city.

I opted for James Fleeting’s gloriously elegant simpleWeather.js, which pulls weather info from Yahoo. It’s beautifully documented and very easy to use. Unless you’re me.

My travel products are a custom post type, which I query to create a carousel. So, for instance, on my hotels page, I query all travel product posts with a category of hotel. I put those into a carousel, and show and hide additional data in a modal, which is where I wanted to show the weather. This meant that I would need to pass the destination city into simpleWeather dynamically.

simpleweather var CodePen

Where I got hooked for TWO PAINFUL DAYS was passing a php variable to my jQuery. I was trying wp_localize_script seven ways to Sunday before it eventually occurred to me that, hey, I could probably just go into my modal include, and say:

var weatherlocation = <?php echo $custom_field['destination']?>;

Yes, it was that easy. In your file, whether it’s a page template or an include or whatever, just open some JavaScript tags, create a new JS variable and assign it a value of your echoed custom field.

(In my case, getting dynamic weather working in each location-specific modal required a bit more code, which I’ll outline in part two. But as a quick and dirty method to pass variables from php to jQuery, this works just fine).