0

I want to create a URL shortener where I use a REST API endpoint request to get a shortened url, e.g.:

mywebsite.com/wp-json/wl/v1/shorten?url=url-to-shorten.com

Where I get a response with a shortened version of the URL that I sent to the URL above, for example mywebsite.com/akjv3, which redirects to url-to-shorten.com.

My question is if this is possible by using standard WordPress methods? I had some look at the documentation but could only find the following:

Short URL

Short Link

Which are not the functionalities I'm looking for as far as I read.

Example of what I'm trying to achieve:

function wl_shortcode() {
    if ( isset( $_GET['url']) ) {
        $shortcode = isset( $_GET['url'] )  ? esc_attr( $_GET['url'] )   : '';

        // CODE HERE TO SHORTEN URL


        return $shorturl;
    } else {
         return false;
    }
}

add_action('rest_api_init', function() {
    register_rest_route('wl/v1', 'shorturl', [
        'methods' => 'GET',
        'callback' => 'wl_shortcode',
    ]);
});

I was thinking of creating the endpoint as above, where the URL gets inserted in a DB table along with a unique key. When accessing mywebsite.com/avuy3, I for instance should be redirected to mywebsite.com/some/path/to/a/page. Is there anyone who is able to guide me in this?

  • So you want a URL shortener, but you want it via a REST API endpoint? This isn't a feature of WordPress and will require bespoke coding, wp_get_shortlink would be the closest to what you want – Tom J Nowell Aug 29 '19 at 11:51
  • @TomJNowell alright. But does wp_get_shortlink, when combined with making a custom endpoint, allow me to achieve what I described in my question? – Condor Aug 29 '19 at 11:53
  • 3
    No, it won't redirect to another URL, what you seek is not in WordPress out of the box, custom code will be required to implement it. Additionally what you're asking for if implemented as is would be open to abuse – Tom J Nowell Aug 29 '19 at 13:45
  • @TomJNowell I updated my question. Is something that I'm asking like in my question considered unsafe? – Condor Aug 30 '19 at 8:30
  • URL shorteners can be used to launch phishing attacks and hide malicious links, you'll want to make sure only authenticated users can create them, or that there are restrictions on where they can lead to avoid problems – Tom J Nowell Aug 30 '19 at 9:26
1

Step 1: Create a new template file in your themes folder named: shorturl.php

<?php
/*
Template Name: Short URLS
Template Post Type: post, page
*/
while ( have_posts() ) :
    the_post();
    $content=get_the_content();
    header('Location: '.str_replace("&amp;","&",$content));
    exit();
endwhile;

Step 2: Create a new php file in your wp-content/plugins/ folder and name it: public-url-shortener.php

<?php
/*
Plugin Name: Public URL Shortener
Plugin URI:
Description: Use the shortcode [urlshortener] in a page to use this plugin.
Version: 1
Author: Burgil
Author URI: https://wordpress.org/plugins/public-url-shortener
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
/**
 * Front end registration
 */
function urlshortener_func( $atts ){
    if(isset($_POST['url'])&&isset($_POST['custom'])){
        $payload='
        <form method="post">
        <input class="input" type="text" value="'.$_POST['url'].'" name="url" placeholder="Paste long url and shorten it">
        <div class="customurl"><label>'.get_home_url()."/".'</label><input id="customkey" class="input" type="text" value="'.$_POST['custom'].'" name="custom" placeholder="Enter a custom link"></div>
        <input class="button button-primary" id="shortbtn" style="display: inline;" type="submit" value="Shorten">
        </form>
        ';
        $isEmpty=false;
        if(empty($_POST['custom'])){$payload=$payload."<h3 style='color:red;border:3px double;width:auto;background: #0000007a;border-radius: 10px;'>ERROR: You entered an empty Custom Link for your shorten URL!</h3>";$isEmpty=true;}
        if(empty($_POST['url'])){$payload=$payload."<h3 style='color:red;border:3px double;width:auto;background: #0000007a;border-radius: 10px;'>ERROR: You entered an empty URL!</h3>";$isEmpty=true;}
        if($isEmpty==false){
            $urltoshort=$_POST['url'];
            $custom_link = sanitize_title_with_dashes( remove_accents( $_POST['custom'] ) );
            $new_post = array(
                'post_title' => $custom_link,
                'post_content' => $urltoshort,
                'post_status' => 'publish',
                'post_date' => date('Y-m-d H:i:s'),
                'post_author' => '',
                'post_type' => 'post',
                'post_category' => array(0)
            );
            if(post_exists( $custom_link )==0){
                $post_id = wp_insert_post( $new_post );
                update_post_meta( $post_id, '_wp_page_template', 'shorturl.php' );
                $payload=$payload."<h3 style='color:green;border:3px double;width:auto;background: #0000007a;border-radius: 10px;'>SUCCESS: Custom Link Created: <a href='".get_home_url()."/".$custom_link."'>".get_home_url()."/".$custom_link."</a></h3>";
            }else{
                $payload=$payload."<h3 style='color:red;border:3px double;width:auto;background: #0000007a;border-radius: 10px;'>ERROR: Custom Link '".get_home_url()."/".$custom_link."' Already Exists!</h3>";
            }
        }
    }else{
        $payload='
        <form method="post">
        <input class="input" type="text" value="" name="url" placeholder="Paste long url and shorten it">
        <div class="customurl"><label>https://www.gtamacro.ga/</label><input id="customkey" class="input" type="text" value="" name="custom" placeholder="Enter a custom link"></div>
        <input class="button button-primary" id="shortbtn" style="display: inline;" type="submit" value="Shorten">
        </form>
        ';
    }
    return $payload;
}
add_shortcode( 'urlshortener', 'urlshortener_func' );

Step 3: Activate The Plugin Public URL Shortener

Step 4: Create a new page in your WordPress and name it URL Shortener

Step 5: Add the following shortcode in the content: [urlshortener]

Now open the page you created, make sure to choose a template that has the get_content() function in it and enjoy.

enter image description here

  • Thank you for your answer. Although this kind of is how I want it to be, this creates a post visible to the whole internet. I'd rather have something that inserts it into the DB with a unique value and then by going to mysitecom/uniquevalue which redirects to the desired website. – Condor Sep 12 '19 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.