Creating a URL shortener tool for your WordPress site can be a great way to manage and track your URLs. In this guide, we’ll walk through how to create a simple URL shortener plugin for WordPress. This plugin will allow users to shorten URLs, track clicks, and manage their shortened URLs through the WordPress admin panel.
Plugin Overview
Our URL shortener plugin will include the following features:
- Shortening URLs: Users can input a long URL and optionally provide a custom short code.
- Redirecting URLs: The plugin will handle redirection from short URLs to their corresponding long URLs.
- Click Tracking: The plugin will track the number of clicks for each shortened URL.
- Admin Management: An admin page to view, manage, and delete shortened URLs.
Step 1: Plugin Setup
First, let’s set up our plugin with basic information and hooks for activation and deactivation.
Plugin Header and Activation Hook
<?php
/*
Plugin Name: URL Shortener Tool
Description: A simple URL shortener tool for WordPress.
Version: 1.1
Author: Ali Shahbaz
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
// Activation hook
register_activation_hook(__FILE__, 'url_shortener_tool_activate');
function url_shortener_tool_activate() {
global $wpdb;
$table_name = $wpdb->prefix . 'shortened_urls';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
original_url text NOT NULL,
short_code varchar(10) NOT NULL,
click_count int NOT NULL DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY short_code (short_code)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
Deactivation Hook
// Deactivation hook
register_deactivation_hook(__FILE__, 'url_shortener_tool_deactivate');
function url_shortener_tool_deactivate() {
global $wpdb;
$table_name = $wpdb->prefix . 'shortened_urls';
$wpdb->query("DROP TABLE IF EXISTS $table_name");
}
Step 2: Creating the Shortener Form
We’ll create a shortcode to display a form where users can input their URLs to be shortened.
// Create shortcode [url_shortener_form]
add_shortcode('url_shortener_form', 'url_shortener_form');
function url_shortener_form() {
ob_start();
?>
<form method="post" action="">
<input type="url" name="original_url" placeholder="Enter URL" required>
<input type="text" name="custom_code" placeholder="Custom Short Code (optional)">
<input type="submit" name="submit_url" value="Shorten URL">
</form>
<?php
return ob_get_clean();
}
Step 3: Handling Form Submission
We need to handle the form submission to store the original URL and generate or validate the short code.
// Handle form submission
add_action('init', 'handle_url_shortener_form');
function handle_url_shortener_form() {
if (isset($_POST['submit_url'])) {
global $wpdb;
$table_name = $wpdb->prefix . 'shortened_urls';
$original_url = esc_url_raw($_POST['original_url']);
$custom_code = sanitize_text_field($_POST['custom_code']);
$short_code = empty($custom_code) ? substr(md5(time()), 0, 6) : $custom_code;
// Check if the short code already exists
$row = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE short_code = %s", $short_code));
if ($row) {
echo '<p>Short code already exists. Please choose another one.</p>';
} else {
$wpdb->insert($table_name, [
'original_url' => $original_url,
'short_code' => $short_code
]);
$short_url = home_url('/') . $short_code;
echo '<p>Shortened URL: <a href="' . esc_url($short_url) . '">' . esc_html($short_url) . '</a></p>';
}
}
}
Step 4: Redirecting Short URLs
To handle redirection, we need to intercept the request and redirect it to the original URL if the short code exists.
// Redirect short URLs and track clicks
add_action('template_redirect', 'handle_short_url_redirect');
function handle_short_url_redirect() {
global $wpdb;
$table_name = $wpdb->prefix . 'shortened_urls';
$request = trim($_SERVER['REQUEST_URI'], '/');
$row = $wpdb->get_row($wpdb->prepare("SELECT original_url, click_count FROM $table_name WHERE short_code = %s", $request));
if ($row) {
$wpdb->update($table_name, ['click_count' => $row->click_count + 1], ['short_code' => $request]);
wp_redirect(esc_url_raw($row->original_url), 301);
exit;
}
}
Step 5: Admin Page for Managing URLs
Finally, we’ll add an admin menu and a page where the admin can view and manage the shortened URLs.
// Admin menu for managing URLs
add_action('admin_menu', 'url_shortener_tool_admin_menu');
function url_shortener_tool_admin_menu() {
add_menu_page('URL Shortener', 'URL Shortener', 'manage_options', 'url-shortener-tool', 'url_shortener_tool_admin_page');
}
function url_shortener_tool_admin_page() {
global $wpdb;
$table_name = $wpdb->prefix . 'shortened_urls';
// Handle URL deletion
if (isset($_POST['delete_url'])) {
$id = intval($_POST['url_id']);
$wpdb->delete($table_name, ['id' => $id]);
}
$urls = $wpdb->get_results("SELECT * FROM $table_name");
?>
<div class="wrap">
<h1>URL Shortener</h1>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th>ID</th>
<th>Original URL</th>
<th>Short Code</th>
<th>Clicks</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($urls as $url) : ?>
<tr>
<td><?php echo esc_html($url->id); ?></td>
<td><?php echo esc_url($url->original_url); ?></td>
<td><?php echo esc_html($url->short_code); ?></td>
<td><?php echo esc_html($url->click_count); ?></td>
<td>
<form method="post" action="">
<input type="hidden" name="url_id" value="<?php echo esc_attr($url->id); ?>">
<input type="submit" name="delete_url" value="Delete" class="button button-primary">
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php
}
Conclusion
In this guide, we’ve built a simple URL shortener tool for WordPress that allows users to shorten URLs, track clicks, and manage their URLs through an admin page. This plugin serves as a foundation that can be extended with more features, such as custom URL validation, analytics, and more.
By following these steps, you now have a functional URL shortener plugin integrated into your WordPress site. Happy coding!
Post a Comment