In the modern digital world, sharing URLs has become a necessity. Whether you’re sharing blog posts, product pages, or special offers, having a clean, short URL can improve your website’s usability, enhance aesthetics, and make links more shareable. One effective way to achieve this is by using a custom URL shortener on your WordPress website.
In this blog, we’ll explore how to create a custom URL shortener plugin for WordPress that uses Base62 encoding to generate unique short URLs. We’ll also walk through how to display these short URLs on the front end of your site, where users can easily copy and share them.
Why Use a Custom URL Shortener in WordPress?
Before diving into the technical details, let’s quickly look at why you might want to create a custom URL shortener:
- Clean and Brandable Links: Custom short URLs can include your website’s domain name, making the links brandable and easier to remember.
- Enhanced User Experience: Short URLs are easier to share, especially on social media or in emails.
- Tracking and Analytics: If integrated with tracking services, you can gather insights into how many people clicked on your shortened links.
- Improved SEO: While short URLs don’t directly impact SEO, they make your content easier to share, which can indirectly boost SEO by improving your site’s visibility and engagement.
Now that we know why it’s important, let’s build the custom URL shortener.
Step 1: Creating the Custom URL Shortener Plugin
We’ll begin by writing a WordPress plugin that handles the URL shortening and redirecting. Our plugin will perform two main tasks:
- Base62 Encoding: We’ll convert the post ID into a base62-encoded string, which will serve as the short URL.
- Redirection: When a user accesses a short URL (e.g.,
/hRY
), the plugin will decode it back to the original post ID and redirect to that post.
Base62 Encoding and Decoding Functions
Base62 encoding is a way to represent numbers using a set of 62 characters (0-9, a-z, A-Z). By converting the post ID into this base, we can create short URLs that are both human-readable and unique.
Here’s the code to encode and decode the URLs:
// Base62 encoding function with mb_substr
function encodeBase62($num) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = strlen($characters);
$encoded = '';
while ($num >= $base) {
$remainder = $num % $base;
$encoded = mb_substr($characters, $remainder, 1) . $encoded; // Use mb_substr to get the character
$num = floor($num / $base);
}
if ($num) {
$encoded = mb_substr($characters, $num, 1) . $encoded; // Use mb_substr to get the final character
}
return $encoded;
}
// Base62 decoding function
function decodeBase62($encoded) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$base = strlen($characters);
$decoded = 0;
$length = strlen($encoded);
for ($i = 0; $i < $length; $i++) {
$char = mb_substr($encoded, $i, 1); // Safe way to get a single character
$decoded = $decoded * $base + strpos($characters, $char);
}
return $decoded;
}
Redirecting Short URLs to Original Posts
When a user visits a shortened URL (e.g., example.com/hRY
), we need to decode it and redirect them to the original post. We will hook into the template_redirect
action to check if the requested URL matches our shortened URL pattern and perform the redirection.
// Redirect from short URL to the post
function custom_url_redirect() {
$requested_url = trim($_SERVER['REQUEST_URI'], '/');
if (empty($requested_url)) return;
$decoded_id = decodeBase62($requested_url);
$post = get_post($decoded_id);
if ($post) {
wp_redirect(get_permalink($post), 301);
exit;
}
}
add_action('template_redirect', 'custom_url_redirect');
Step 2: Displaying Short URL with Copy Button
Once we’ve encoded the post ID, we need to provide users with an easy way to copy and share the shortened URL. We’ll create a shortcode to display the short URL and a “Copy” button in the front-end.
// Add the shortcode to display the short URL on the front-end
function custom_short_url_shortcode($atts) {
global $post;
if (!$post) return;
$post_id = $post->ID;
$short_url = encodeBase62($post_id);
$full_short_url = home_url("/$short_url");
// Return the HTML for the short URL and the copy button
$output = '<div class="short-url-container">';
$output .= '<span>Your custom short URL:</span>';
$output .= '<div class="input-container">';
$output .= '<input type="text" value="' . esc_url($full_short_url) . '" id="short-url" readonly />';
$output .= '<button class="copy-button" onclick="copyToClipboard()">Copy</button>';
$output .= '</div>';
$output .= '</div>';
$output .= '
<script>
function copyToClipboard() {
var copyText = document.getElementById("short-url");
copyText.select();
copyText.setSelectionRange(0, 99999); // For mobile devices
document.execCommand("copy");
alert("Copied: " + copyText.value);
}
</script>';
return $output;
}
add_shortcode('short_url', 'custom_short_url_shortcode');
Enhancing the User Interface
To make the short URL input and copy button look more user-friendly, we’ll add some CSS styles. We’ll use a clean, modern design with a flexible layout, and style the copy button for better interactivity.
// Add some basic styles for the shortcode output
function custom_short_url_styles() {
echo '<style>
.short-url-container {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
margin-top: 20px;
font-family: Arial, sans-serif;
}
.short-url-container span {
font-size: 18px;
color: #333;
margin-bottom: 10px;
font-weight: 600;
}
.input-container {
display: flex;
align-items: center;
border: 1px solid #ddd;
border-radius: 4px;
padding: 5px;
width: 100%;
max-width: 500px;
background-color: #f9f9f9;
}
.input-container input {
flex-grow: 1;
border: none;
padding: 10px;
font-size: 16px;
color: #333;
background-color: #f9f9f9;
box-sizing: border-box;
border-radius: 4px;
}
.input-container button {
padding: 10px 15px;
font-size: 16px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-left: 10px;
}
.input-container button:hover {
background-color: #45a049;
}
.input-container input:focus {
outline: none;
box-shadow: 0 0 5px rgba(0, 123, 255, 0.5);
}
</style>';
}
add_action('wp_head', 'custom_short_url_styles');
Step 3: Using the Shortcode in WordPress Posts
Now that the functionality is in place, you can use the
shortcode in your posts to display the shortened URL and the copy button.
You can try this link: https://guerzilla.com/al. It would redirect to the original blog post.
Where to Place the Short URL for the Best User Experience
- At the End of the Post: This is the most common location for sharing links. After reading the content, users can easily copy and share the shortened URL.
- After Key Sections: If your post has specific sections or highlights that are meant to be shared, placing the short URL after those sections is a good option.
- Floating or Sticky Button: For important posts (e.g., offers or announcements), a floating button with the short URL could be visible at all times as users scroll.
Conclusion
By creating a custom URL shortener for WordPress using Base62 encoding, you can enhance the user experience and provide a shareable, brandable link for your posts. The functionality we’ve discussed here ensures that your posts are easy to share, and the added copy button lets users quickly grab the URL for social sharing, email, or messaging.
With just a few lines of code, you can implement this feature on your WordPress website, improving how users interact with your content. Try it out, and see how this simple feature can boost the shareability of your posts!
Leave a Reply