Adding Custom Code to Wordpress

Adding custom code to WordPress


Now that my shop is functional, it is time to add some extra functionality to the site, and a showcase of some technologies. Adding custom code to WordPress can be achieved by creating files within your theme folder, where the style sheet is kept.

It can be tricky to add code in to WordPress as the site has it's own scripts that run when a site boots, which are essential to the functionality of the site. If these fail to run, or are run in a different order, then your site could face issues.  

To avoid this conflict, a 'functions.php', file is added to the folder. Overall, this file allows users to add or change default features within your theme. In this case, this will allow the queuing of script files, including my custom script.

It is now time to add some functionality to the site using API's and a selection of client-side technologies.


Weather

After signing up to use OpenWeatherMap's API, you are provided with an API key which can be used to access weather from any city in the world. An API key is used to identify who is making a request to the API, and is completely unique to each user. This system is beneficial for numerous reasons such as spam prevention, and to limit malicious requests. Their free tier allows for a 3 day and 5 day forecast, and several other things. Below is a snippet of my request to OpenWeatherMap's API.



The snippet above starts by setting out inital variables needed within the functionality of the script, such as an array of day names. Importantly, a variable names API is set, to a request location for the OpenWeatherMap's API, including my secret key.

A GET request is then used using the JQuery helper $.get(), with the GET URL held within the brackets. Once the request is completed, JQuery's .done() is called to call a function containing the requested data, status of request and the 'jqxhr' object used to handle the request, also aiding in cross-domain data transfer.

The JQuery each() function is used on the resulting xml to cycle through the results - a 5 day forecast from Tom Land (technically just a place named 'Tom' - but for the purposes of this site we can call it Tom Land). Contained in each forecast segment of 3 hours is the temperature, time, and weather symbol. 

These results are dynamically added to the page using the JQuery appendTo() function, which begins by finding an element, then attaching the argument of the function to the element. In this case, I used the temperate and time.


Expanding on the done() function, there are also two partners to this function, fail(), and always(). These are self-explanatory, as anything in the fail() function will be triggered should the request fail, and the always() function will always be triggered. Below is an example of what is found in these functions.



From this block of code we can deduce that "Sending request" will always be triggered when the request is sent. Also, if the request fails then the error status and text will be shown in the console.

Although, this script does not automatically activate when entering the page you wish. First, you must create the page you wish to run the script using WordPress, then functions.php must be modified.

This is telling WordPress to call the function myScripts, which when visiting the chosen page ('weather') will queue the script found in '/js/weatherapi.js'.


Top 10 shows

To showcase another use of technologies, I will be attempting to implement an API from Apple using AJAX. This API will return the top 10 most popular TV episodes right now on their service. Unlike the previous API, this API will return data in JSON, not xml. These two data types are most common data structures returned when using an API, and they both serve the same purpose which is to define properties and attributes. Although, JSON is smaller in size than XML, easier to read, and can define arrays so is the preferred choice for modern API's.

Below is an example of my request to Apple to access the top 10 shows.


As you can see, like last time, the API location is set initially, which points to the RSS feed for ITunes. Note that this URL ends with '/json' which is indicative of the type of data that will be returned.

From there, a request is made to the API URL using the getJSON() jquery helper. This is simply an HTTP GET request but expects JSON to be returned, so prepares for such data. 

Like the previous requests, this function has contains conditions for when the request is a success, when it fails, and for when the request begins. 

If the request is a success, the array of results is looped through and printed to the screen using 'appendTo()'. Otherwise, if the request fails, the error status and error message is taken in to a function to be printed out to the console. 

This took some figuring out, as the the request would work perfectly until I put it on to WordPress. An error message was given even before the request was made. The error is shown below in the console:


What this error means is that the script is trying to access a method of an object it has no knowledge of. After searching for a fix, I can across a site that explains that sometimes an error occurs when attempting to use Jquery within WordPress where it will conflict with the default WordPress scripts. The solution can be found here: https://digwp.com/2009/06/including-jquery-in-wordpress-the-right-way/. This site explains the 'right way' to add JQuery to WordPress, and at the bottom shows a method of being 'extra safe' when adding scripts, that will avoid conflicts. It does not explicitly say state the issue I was having, but fixed it nonetheless.


Header effects

As an additional piece of Jquery, I tried my hand at some Jquery effects. JQuery gives you some pre-determined effects for divs and images. As this site is supposed to be non-serious (a bit cheesy, actually), I thought some effects would suit it nicely. all JQuery effects can be found here at w3 schools: https://www.w3schools.com/jquery/jquery_ref_effects.asp. 

I settled on making the header fade in when the page loads. This seemed as simple as targetting the id of the header, and attaching .fadeIn() to it, but there was a slight issue. As JQuery uses a copy of the DOM which is already loaded the header would do nothing, as the header was already on the screen.

The solution to this issue was to hide the header on load, then to begin to fade the header in using the id of the image, as shown in the snippet below.

As with the top10 request, I thought it best to put this JQuery in to no-conflict mode too. 

At the end of adding this custom code, my functions.php contains 3 functions, for each script: OpenWeather, Apple top 10, and for the header. 


That is the end of my work with WordPress! I will now move on to creating a CRUD application on my Xampp server using the Reddit API. 

Comments

Popular posts from this blog

Creating a Reddit post

Reddit Authentication & Access tokens

Deleting a Reddit Post