In today’s digital world, URLs can get lengthy and complex, especially when sharing content online. A long, cumbersome URL can be difficult to share or remember. That’s where a URL shortener comes in handy. This blog post walks you through creating a simple URL shortener plugin for WordPress that allows users to generate short, shareable links for any URL they input.
Why Use a URL Shortener?
URL shorteners are a powerful tool, particularly for social media, marketing campaigns, and sharing links through emails or texts. They provide an easier way to handle lengthy URLs by converting them into compact versions, making sharing more convenient and professional.
With the WordPress plugin you’ll create, users can quickly shorten URLs directly from your site. Let’s dive into the code and break down how to build this plugin!
Step-by-Step Guide to Creating a URL Shortener Plugin
1. Setting Up the Plugin
To start, you’ll need a basic structure for your plugin. In the WordPress plugins folder (wp-content/plugins/
), create a new folder named url-shortener
. Inside this folder, create a PHP file called url-shortener.php
. Add the following header to this file:
<?php
/**
* Plugin Name: URL Shortener
* Description: A simple URL shortener plugin.
* Version: 1.0
* Author: Asif Khan
*/
This defines your plugin’s name, description, version, and author. Now WordPress can detect and install your plugin.
2. Adding Styles and Scripts
To make your plugin visually appealing and functional, you’ll want to add some CSS and JavaScript. This is where we define the layout of the plugin and how the shortening functionality works.
We will use wp_head
to load the necessary CSS and JavaScript in the plugin. Here’s the code for that:
// Enqueue CSS and JavaScript inline to avoid conflicts
function url_shortener_enqueue_scripts() {
?>
<style>
/* Add styles for the plugin */
.url-shortener-plugin {
font-family: Arial, sans-serif;
margin: 20px;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
background-color: #f9f9f9;
}
.url-shortener-main h1 {
font-size: 2em;
margin-bottom: 10px;
color: #333;
}
/* Add more styles here */
</style>
<script>
async function shortenURL() {
var urlInput = document.getElementById("urlInput").value;
var button = document.getElementById("shortenBtn");
var spinner = document.querySelector("#shortenBtn .spinner");
if (!urlInput) {
alert("Please enter a URL");
return;
}
button.disabled = true;
spinner.style.display = "block";
try {
var response = await fetch('https://tinyurl.com/api-create.php?url=' + encodeURIComponent(urlInput));
var shortenedURL = await response.text();
document.getElementById("shortenedURL").innerHTML = shortenedURL;
document.getElementById("shortenedURL").href = shortenedURL;
document.getElementById("result").style.display = "block";
} catch (error) {
console.error('Error shortening URL:', error);
} finally {
button.disabled = false;
spinner.style.display = "none";
}
}
function copyToClipboard() {
var copyText = document.getElementById("shortenedURL");
var textArea = document.createElement("textarea");
textArea.value = copyText.href;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
document.body.removeChild(textArea);
alert("Copied to clipboard!");
}
</script>
<?php
}
add_action('wp_head', 'url_shortener_enqueue_scripts');
The code above includes CSS for the plugin’s layout and a JavaScript function to handle the URL shortening. It sends the user’s input to the TinyURL API to generate a shortened URL, which is displayed on the page.
3. Creating the Shortcode
To integrate this functionality into any page or post, we’ll use a WordPress shortcode. The shortcode function generates the form and displays the shortened URL once processed.
function url_shortener_shortcode() {
ob_start();
?>
<div class="url-shortener-plugin">
<div class="url-shortener-main">
<h1>URL Shortener</h1>
<p>Instantly shorten your long URLs into short, shareable links!</p>
<div class="url-input">
<input type="url" id="urlInput" placeholder="Enter URL">
<button onclick="shortenURL()" id="shortenBtn">
Shorten
<div class="spinner"></div>
</button>
</div>
<div id="result">
<p>Shortened URL:</p>
<a href="" target="_blank" id="shortenedURL"></a>
<button onclick="copyToClipboard()">Copy</button>
</div>
</div>
</div>
<?php
return ob_get_clean();
}
add_shortcode('urlshortener', 'url_shortener_shortcode');
This shortcode function generates the HTML for the plugin, including the input field for the URL, a button to trigger the shortening process, and a display area for the shortened URL and copy button.
4. Using the Plugin
Now that the plugin is created, you can install and activate it from the WordPress dashboard. To use the plugin on a page or post, simply add the following shortcode:
[urlshortener]
This will insert the URL shortener form wherever you place the shortcode.
Live Test: https://apycoder.com/url-shortener/
Final Thoughts
Creating your own URL shortener plugin is an excellent way to extend WordPress functionality and provide users with a helpful tool. This simple yet effective plugin uses external APIs to generate shortened URLs and is easily customizable. You can extend this further by integrating different URL-shortening services or adding custom features like analytics.
By building this plugin, you gain valuable hands-on experience with WordPress development, including enqueueing scripts, handling user input, and using shortcodes.
Happy coding!
About the Author
Asif Khan is a passionate WordPress developer with experience in creating user-friendly plugins. You can find more tutorials and plugins on ApyCoder. Follow me on YouTube for more WordPress development tips and tricks!