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:
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?