Here we have set up a very simple image gallery that firstly grabs 6 images from the Pixabay API, loops through the returned images and outputs them into a slider/gallery using Fotorama jQuery image gallery. Below is a screenshot of what our gallery looks like.
Setting up the API
We are using the Pixabay API which is very simple to use. It simply requires you to register (via Google or email) and you are instantly given an API key that you can use.
Our endpoint settings in WPGetAPI are shown below. Because we will be using the template tag, you need to ensure that the Results Format is set to PHP array data.
Checking our API data
We can check the output of our API call by using the following snippet. This snippet can be pasted into your theme files or you could use a PHP code snippet plugin such as this one – https://wordpress.org/plugins/insert-php-code-snippet/
The code snippet plugin allows you to create ‘code snippets’ with whatever code you like (such as the code below) that can then be inserted into a page using a shortcode. It is very handy.
// call the api and store the response in $data $data = wpgetapi_endpoint( 'pixabay', 'api', array('debug' => false) ); // output the result of $data using our inbuilt 'pretty print' function wpgetapi_pp( $data );
The data should look something like in the below image.
Looping through images
Below is the code we used to add the required scripts, call the API using the wpgetapi_endpoint() function and then loop through the images and output them. This code can be added to a theme template file or you could use the code snippets plugin mentioned earlier.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.css" rel="stylesheet"> <script src="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.js"></script> <?php // call the api and store the response in $data $data = wpgetapi_endpoint( 'pixabay', 'api', array('debug' => false) ); // make sure we have the data if( isset( $data['hits'] ) ) : ?> <!-- wrap in our fotorama div --> <div class="fotorama" data-nav="thumbs"> <?php // loop through the images foreach ( $data['hits'] as $index => $image ) : ?> <!-- add the image URL into a HTML <img> --> <img src="<?php esc_attr_e( $image['webformatURL'] ); ?>" /> <?php endforeach; ?> </div> <?php endif; ?>
Read more info on the Fotorama image gallery plugin here.