Implementing a URL Shortener

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. Is there anyone who has any idea how to do this/can put me on the right path?

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’,
]);
});

Read more here:: Implementing a URL Shortener

Leave a Reply

Your email address will not be published. Required fields are marked *