In this tutorial we will be coding a WordPress plugin that displays random entries from the ZenQuotes API on your website using a shortcode. With this snippet, your quotes can be put into posts, pages, and widgets using one simple tag.
What you will learn
By the end of this tutorial you will know how to register a WordPress plugin, cache data from a remote API, and register a shortcode.
This plugin is an adaptation from a previous tutorial where we stored a batch of quotes from the ZenQuotes API to a local text file. This cache is stored locally rather than calling the API on every page load and will automatically update each hour.
We are now adding the ability to use this snippet in WordPress and registering a shortcode. Simply activate the plugin and insert your shortcode to display a random quote on each page load.
Step 1: Register the Plugin
Plugins are essentially scripts that you can add to your WordPress website to extend or modify its functionality without needing to modify the core WordPress code or theme. Plugins allow you to add new features, change the way your website looks, or enhance its performance.
Plugins are created using PHP, which is a popular programming language used to develop web applications. They can also use other web technologies such as HTML, CSS, and JavaScript to create interactive features.
WordPress provides a plugin API (Application Programming Interface), which is a set of functions and hooks that allow developers to create plugins that integrate with the core WordPress system. This means that plugins can interact with WordPress, access its data, and modify its behavior.
Plugins can be installed and activated from the WordPress dashboard, and can be easily deactivated or uninstalled if you decide you no longer need them. Unlike code that is written in the theme functions.php file, the plugin functionality is available no matter which theme is active.
Setup the Project Folder
First, create a new folder on your machine and name it wp-zenquotes-shortcode-plugin.
Next, create a new PHP file in this folder and give it the name wp-zenquotes-shortcode-plugin.php
Inside this PHP file paste the following code, this is what will register your file as a plugin with WordPress:
PHP
<?php /* Plugin Name: ZenQuotes.io Shortcode Description: Place random ZenQuotes on your website using the shortcode insert-zenquotes-block Author: ZenQuotes.io Author URI: https://zenquotes.io/ Version: 1.0.0 */
That is all we really need to tell the WordPress core installation about the plugin details to get started with development. Any code within this file will now be executed on every page load once the plugin is installed and activated in WordPress.
Step 2: Insert the ZenQuotes local cache snippet
For this example we are using curl in PHP to retrieve the API contents to a text file that is created within the plugins folder. The code will store 50 quotes on your local machine rather than call the ZenQuotes API each time you want to load a quote.
Storing the quotes locally provides a much faster load time on your website and less load on the API server. This plugin will check the last updated file time on each page load and refreshes the quotes text file on your server after about an hour, eliminating the need for an API key.
PHP
// Main API Function, checks local cache file and returns the quotes array function wp_zenquotes_api_call() { // Define the plugin directory path $dir = plugin_dir_path( __FILE__ ); // Path to store your cache text file, default is plugin directory $filePath = $dir."zenquotes.txt"; // ZenQuotes API URL, returns an array of 50 random quotes $url = "https://zenquotes.io/api/quotes"; // Cache update time in seconds $expireTime = (60 * 60); // Update every hour // Get file last update time or return 0 if no file exists $fileTime = file_exists($filePath)? filemtime($filePath) : 0; // Check whether data needs to be updated if( ($fileTime + $expireTime) < time() ) { // Get API Response using curl $ch = curl_init(); // Initialize curl curl_setopt($ch, CURLOPT_URL, $url); // Set url curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set return transfer $json = curl_exec($ch); // Execute the response curl_close($ch); // Close curl // Open the cache file $cacheFile = fopen($filePath, "w"); // Write the new data to file and close if($cacheFile && $json) { fwrite($cacheFile, $json); fclose($cacheFile); } } // Decode json response and assign the quotes to an array $jsonArr = json_decode(file_get_contents($filePath),true); // Shuffle the array to get a random value at position 0 shuffle($jsonArr); // Return the decoded json array return $jsonArr; } // End Function
This is the main function responsible for handling the API. It detects the plugin directory, calls the ZenQuotes API and saves the data to a text file in the plugin folder. The next function is simply responsible for formatting the API data into HTML:
PHP
// Custom short code function function wp_zenquotes_shortcode() { // Call the ZenQuotes API function $jsonArr = wp_zenquotes_api_call(); // Define the HTML output $output = (isset($jsonArr[0]['q']))? '<div class="zenquotes-shortcode-block">“'.$jsonArr[0]['q'].'” — '.$jsonArr[0]['a'].'</div>' : '<small><em>API Error</em></small>'; // Return the output return $output; } // End Function
Step 3: Register the Shortcode
WordPress Shortcodes are a powerful tool that can help you add dynamic content to your website or blog with ease. Shortcodes are enclosed in square brackets like this: [my-shortcode], and when they are inserted into a post or page, they are replaced with some dynamic content.
When you insert this shortcode into your post or page, WordPress will replace it with the appropriate YouTube embed code, allowing your visitors to watch the video without leaving your website.
Shortcodes are easy to create and can be used for a wide variety of purposes, such as embedding videos, displaying image galleries, or adding contact forms to your website. They can be created using PHP code, and WordPress provides a Shortcode API that makes it easy to create, register, and use your own custom shortcodes.
Register your random quote from the previous step as a shortcode named [insert-zenquotes-block] using the snippet below:
PHP
// Register the shortcode function with WordPress add_shortcode('insert-zenquotes-block', 'wp_zenquotes_shortcode');
This line will register the shortcode insert-zenquotes-block in WordPress and associate its output with the wp_zenquotes_shortcode() function.
Step 4: Install the Plugin
Once you have the code completed you can install the plugin in one of two ways:
1. Dashboard Upload
Send the plugin folder you created to a .zip file. In Microsoft Windows you can right click on the folder and select Send To Compressed Folder.
Next, navigate to your WordPress Dashboard and select Plugins > Installed Plugins. From here, click on the Add New button and then click the Upload Plugin button to display the upload form.
Use the upload form to select the Zip Folder you just created. The entry will be added to your list of available plugins.
Click on the Activate link to enable the plugin. There are no configurable settings from the Dashboard.
2. Manual FTP Upload
If you would rather upload the files to your server manually, you can use a program like FileZilla to access your website directory. From here, navigate to /wp-content/plugins/ and upload your plugins folder (uncompressed, not zipped).
The result would be: /wp-content/plugins/wp-zenquotes-shortcode-plugin
After you upload the files, navigate to WordPress Dashboard > Plugins > Installed Plugins. From here, you should see the new plugin available in the list.
Click on the Activate link to enable the plugin. There are no configurable settings from the Dashboard.
Step 5: Place the Shortcode
To display a random quote on your website, simply use the shortcode [insert-zenquotes-block] as defined in the code on any post, page, or text widget. Your users will see a new quote on each page load, this plugin is perfect for the sidebar or footer section.
WordPress
[insert-zenquotes-block] Inspirational quotes provided by <a href="https://zenquotes.io/" target="_blank">https://zenquotes.io/</a>
Note: We require that you show attribution with a link back to https://zenquotes.io/ when using the free version of our API.
Step 6: Style your quote
You can change the CSS style of your quote by adding the appropriate classes to the WordPress Theme Customizer > Additional CSS. Change the properties as needed.
CSS
.zenquotes-shortcode-block{font-size: 1em; font-family:serif; color:#000000;}
Expanding Further
You could expand on this plugin by customizing the cache update interval, CSS class handler, API error message, and HTML format to fit your needs. In a later lesson, we will show how to create a settings page that allows you to customize these options from the WordPress Dashboard.
Completed Code
The completed code example with all of the snippets above is included below:
PHP
<?php /* Plugin Name: ZenQuotes.io Shortcode Description: Place random ZenQuotes on your website using the shortcode insert-zenquotes-block Author: ZenQuotes.io Author URI: https://zenquotes.io/ Version: 1.0.0 */ // Main API Function, checks local cache file and returns the quotes array function wp_zenquotes_api_call() { // Define the plugin directory path $dir = plugin_dir_path( __FILE__ ); // Path to store your cache text file, default is plugin directory $filePath = $dir."zenquotes.txt"; // ZenQuotes API URL, returns an array of 50 random quotes $url = "https://zenquotes.io/api/quotes"; // Cache update time in seconds $expireTime = (60 * 60); // Update every hour // Get file last update time or return 0 if no file exists $fileTime = file_exists($filePath)? filemtime($filePath) : 0; // Check whether data needs to be updated if( ($fileTime + $expireTime) < time() ) { // Get API Response using curl $ch = curl_init(); // Initialize curl curl_setopt($ch, CURLOPT_URL, $url); // Set url curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set return transfer $json = curl_exec($ch); // Execute the response curl_close($ch); // Close curl // Open the cache file $cacheFile = fopen($filePath, "w"); // Write the new data to file and close if($cacheFile && $json) { fwrite($cacheFile, $json); fclose($cacheFile); } } // Decode json response and assign the quotes to an array $jsonArr = json_decode(file_get_contents($filePath),true); // Shuffle the array to get a random value at position 0 shuffle($jsonArr); // Return the decoded json array return $jsonArr; } // End Function // Custom short code function function wp_zenquotes_shortcode() { // Call the ZenQuotes API function $jsonArr = wp_zenquotes_api_call(); // Define the HTML output $output = (isset($jsonArr[0]['q']))? '<div class="zenquotes-shortcode-block">“'.$jsonArr[0]['q'].'” — '.$jsonArr[0]['a'].'</div>' : '<small><em>API Error</em></small>'; // Return the output return $output; } // End Function // Register the shortcode function with WordPress add_shortcode('insert-zenquotes-block', 'wp_zenquotes_shortcode');