How to Create Shortener URL Wordpress Plugins

in #php7 years ago (edited)

Go to your \wp-content\plugins path, create new folder with name shortener.

shortener-plugin-1.png

Create new PHP file in shortener folder with name shortener.php.

shortener-plugin-2.png

Write this code:

<?php 
/*
Plugin Name: URL Shortener
Plugin URI: http://inochisoftware.com
Description: Create shortener URL
Author: Novian Agung
Version: 1.0
Author URI: http://inochisoftware.com
*/

global $shortener_db_version;
global $shortener_table_name;

$shortener_db_version = '1.0';

/* Create new table in your Wordpress database */
if ( ! function_exists( 'shortener_install' ) ) :
function shortener_install() {
    global $wpdb;
    global $shortener_db_version;

    $table_name = $wpdb->prefix . 'direct_url';
    $shortener_table_name = $table_name;
    
    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
        intId MEDIUMINT(9) NOT NULL AUTO_INCREMENT,
        strName VARCHAR(20) NOT NULL,
        strUrl VARCHAR(250) DEFAULT '' NOT NULL,
        PRIMARY KEY (intId)
    ) $charset_collate;";
    
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    
    dbDelta( $sql );
    
    /* Add new option/saving key on meta Wordpress */
    add_option( 'shortener_db_version', $shortener_db_version );
    add_option( 'shortener_table_name', $shortener_table_name );
    
    update_option( "shortener_db_version", $shortener_db_version );
}
endif;

/* Register function "shortener_install" to Wordpress platform */
register_activation_hook( __FILE__, 'shortener_install' );

/* Check for plugin update */
if ( ! function_exists( 'shortener_update_db_check' ) ) :
function shortener_update_db_check() {
    global $shortener_db_version;
    if ( get_site_option( 'shortener_db_version' ) != $shortener_db_version ) {
        shortener_install();
    }
}
endif;

/* Add new action to Wordpress platform when plugin loaded */
add_action( 'plugins_loaded', 'shortener_update_db_check' );

/* CORE FUNCTION */

/* Create randoming key for URL id */
if ( ! function_exists( 'shortener_generate_key' ) ) :
    function shortener_generate_key($length = 12) {
        $pool = array_merge(range(0,9), range('a', 'z'), range('A', 'Z'));
        $key = "";
        for ($i=0; $i < $length; $i++) {
            $key .= $pool[mt_rand(0, count($pool) - 1)];
        }
        return $key;
    }
endif;

/* Saving key to database (new table) */
if ( ! function_exists( 'shortener_generate_url' ) ) :
function shortener_generate_url($url) {
    global $wpdb;
    $table_name = get_site_option( 'shortener_table_name' );
    
    $name = '';
    
    /* Checking for key has already exist */
    $sql = $wpdb->prepare("SELECT `strName` FROM $table_name WHERE `strUrl` = %s", $url);
    $last_name = $wpdb->get_var($sql);
    
    if (empty($last_name)){
        /* Generate a key */
        $name = shortener_generate_key();
        
        /* Insert when key not exist */
        $sql = $wpdb->prepare("INSERT INTO $table_name (`strName`,`strUrl`) values (%s, %s)", $name, $url);
        $wpdb->query($sql);
    } else {
       $name = $last_name;
    }
    
    return $name;
}
endif;

/* Create a new Wordpress short code */
if ( ! function_exists( 'shortener_url_func' ) ) :
function shortener_url_func( $atts, $text = "" ){
    $atts = shortcode_atts( 
        array(
            'url' => ''
        ), 
        $atts, 'short' );
    
    $url = $atts['url'];
    
    /* Get your blog/web URL */
    $main_url = get_site_url();
    
    /* Generate key for URL input */
    $key = shortener_generate_url($url);
    
    /* Generate new URL */
    $shortener_url = $main_url . '/goto/' . $key;
    
    return '<a href="' . $shortener_url . '" title="' . $text . '" target="_blank">' . $text . '</a>';
}
endif;

/* Add a new short code to Wordpress */
add_shortcode( 'short', 'shortener_url_func' ); 

/* Create a redirect URL function */
if ( ! function_exists( 'shortener_redirect_url' ) ) :
function shortener_redirect_url(){
    global $wpdb;
    global $wp_query;
    
    /* When error 404 found */
    if(is_404()){
        /* Get Wordpress query */
        $query = $wp_query->query;
        
        if ($query){
            /* Get attachment field */
            $attachment = $query["attachment"];
            
            /* If attachment not found then name field */
            if (!$attachment){
                $attachment = $query["name"];
            }
            
            /* If name not found then pagename field */
            if (!$attachment){
                $pagename = $query["pagename"];
                
                /* If pagename found */
                if ($pagename){
                    /* Explode pagename value then get attachment key */
                    $arr_pagename = explode("goto/", $pagename);
                    
                    if (count($arr_pagename) == 2){
                        $attachment = $arr_pagename[1];
                    }
                }
            }
            
            /* If attachment found then name field */
            if ($attachment){
                /* Make sure length $attachment is 12 */
                if (strlen($attachment) == 12){
                    $table_name = get_site_option( 'shortener_table_name' );
                    
                    /* Get attachment key from database */
                    $sql = $wpdb->prepare("SELECT `strUrl` FROM $table_name WHERE `strName` = %s", $attachment);
                    $url_redirect = $wpdb->get_var($sql);
                    
                    if ($url_redirect){
                        /* Redirect page */
                        if ( wp_redirect( $url_redirect ) ) {
                            exit;
                        }
                    }
                }
            }
        }
    }
}
endif;

/* Add a new action to Wordpress */
add_action('template_redirect', 'shortener_redirect_url' );
?>

Save your code. Open your Wordpress dashboard, go to Plugins page option. Activate your plugin.

shortener-plugin-3.png

Create a new Post. For example, write this:

Visit my [short url="http://www.facebook.com/"]Facebook[/short] to ... ...

shortener-plugin-4.png

Save and publish your post then visit your post.

shortener-plugin-5.png

See, your link in post (http://www.facebook.com) will convert to shorten URL. Try to clik the link.

Sort:  

Congratulations @cerutu! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You made your First Vote
You made your First Comment
You got a First Reply

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!