WP plugin development using jQuery | XML | OpenWeather API #1
I'd like to display some weather information for the city of Glasgow. For this task I'm going to use Open Weater API which can return current weather and forecast data in JSON or XML format. Then I'll use jQuery - JavaScript library for DOM manipulation and AJAX calls.
How to write and use WordPress plugin
To create plugin we need to go to the location root/wp-content/plugins/ and create new folder (preferred option) or just single php file with unique plugin name.
The file need to have some information (plugin name, author, version, etc.) to be properly identified by WordPress as a plugin. This need to be added at te top of the file.
Then plugin need to be activated from wp-admin dashboard, plugins menu
Plugin uses add_shortcode() native WordPress method that allows to declare name and callback function which will be executed when given name will be added to the page or post(inside the square brackets). I created new Page called Glasgow Weather and calling this shortcode name which executes the assigned function. More info on Shortcode API here.
Adding jQuery to the plugin
To be able to use jQuery in our plugin we need to import jQuery library using wp_enqueue_script() method, when we give name and required URL for the file.
JavaScript cannot be written directly inside plugin php file therefore I created another app.js file which will be imported into the function which will be executed in desired location.
Short jQuery script to test if its working. It should create the new paragraph and append it to div with class "entry content"...
Result - nothing new appeared on the screen. Quick jump to web browser developer tools (great place for html / javascript errors debugging) with F12 and we can se an error - $ is not a function. The problem arises when a different system grabs the $ variable. You have multiple $ variables being used as objects from multiple libraries, resulting in the error.
When I console logged jQuery it showed that this function exist in the system so library was loaded so I decided to locally assign it to the $ sign.
Error has gone but the new paragraph hasn't appear on the screen. Solution for that problem was to execute test code inside jQuery's ready() method which is called for the document object.
And the result... finally jQuery code has been added to the page.

Comments
Post a Comment