JSON data is ugly
API data is usually returned in JSON string format, which is not very pretty at all and probably not how you want to display your API data.
PHP arrays are ugly
Your data may also be returned as PHP array data, which is also not pretty and likely not how you want your API data displayed.
If you know PHP and are comfortable working in theme files, then this data won’t be an issue. But if you don’t know how to work with this data, read on to find out how we can easily format this into a nice HTML format.
Format API data as HTML, easily
The PRO Plugin introduces a new parameter to the
[wpgetapi_endpoint] shortcode, as well as to the template tag, that will allow us to display our data as HTML on your page. We will look at the shortcode and see how easy it is.
We simply need to add the ‘format’ attribute to the shortcode and set it to ‘HTML’ as shown below.
[wpgetapi_endpoint api_id='quotable' endpoint_id='random' format='html']
The HTML output
The output will now look something like the below. It is still not perfect, but looks much better and we can now freely style it with some CSS.
When we look at the source code of our new HTML data, this is when we can start to see how this could be used to make things look a bit prettier. If you know CSS, then you can make this look basically any way you want to.
You will notice that CSS classes are automatically created by using the keys as the class names (prefixed with wpgetapi_). The HTML can now be easily styled using CSS.
There are 6 additional shortcode attributes that get added with the PRO Plugin. These attributes allow you to:
- Set the HTML tags that are generated – can be div, li or span tags
- Include labels on each item – takes the key and turns this into a label, wrapped in its own tag ie. Author: Will Rogers
- Select any field that has a URL
- Use the URL to link another field – such as adding a link to a Title
- Image attribute that let you turn an image URL into an actual image, rather than just displaying the URL
- Prepend the image URL – some API’s will return relative image URLs so this attribute allows us to prepend a full URL
Let’s look in detail at how each of these attributes works and how we can apply them to our shortcode.