Customize Native WordPress Shortlink URL Structure

Print View Mobile View

WordPress LogoWordPress comes with an integrated shortlink function that minimizes the need for a plugin to create shortlinks for posts and pages. If you look at your blog post’s source code, you should be able to see a line like this:

<link rel='shortlink' href='http://domain.com/?p=123' />

A shortlink structure would always be with ?p= syntax and the ID of the post, unless of course you are using a plugin that customizes this URL.

If you’d like to customize the native WordPress shortlink URL structure for branding or any other purpose, here’s how you can do it without modifying core files or using a plugin.

The code in this post will generate shortlink with this structure: http://domain.com/l/123. However, you can easily alter code according to your own preference.

Note: You should be using a custom permalink structure for this to work.

Custom Rewrite Rules

Add this code at the top of your website’s root .htaccess file:

RewriteEngine On
RewriteRule ^l/(d+)$ index.php?p=$1 [L]

Or if you want a PHP based solution, drop this code into your theme’s functions.php file:

function st_add_rewrites()
{
	add_rewrite_rule( '^l/(d+)$', 'index.php?short=$matches[1]', 'top' );
}
add_action( 'init', 'st_add_rewrites' );

function st_query_vars( $vars )
{
	$vars[] = 'short';
	return $vars;
}
add_filter( 'query_vars', 'st_query_vars', 10, 1 );

The will add a rewrite rule that asks to redirect l followed by a slash and a string of digits to index.php?short=string_of_digits.

Redirect Post

Next add this function below the previous one:

function st_shortlink_redirect()
{
	if( ! get_query_var( 'short' ) ) return;
	global $wp_query;

	$id = absint( get_query_var( 'short' ) );
	if( ! $id )
	{
		$wp_query->is_404 = true;
		return;
	}

	$link = get_permalink( $id );
	if( ! $link )
	{
		$wp_query->is_404 = true;
		return;
	}

	wp_redirect( esc_url( $link ), 301 );
	exit();
}
add_action( 'template_redirect', 'st_shortlink_redirect' );

This will check if the short variable is present. If it exists, post permalink is retrieved and the user is taken to the actual post. If not, a 404 error is send.

Enable Custom Short Link Everywhere

Finally, add this last piece of code to the functions file as well:

function st_get_shortlink( $link, $id, $context )
{
	if( 'query' == $context && is_single() )
	{
		$id = get_queried_object_id();
	}
	return home_url( 'l/' . $id );
}
add_filter( 'get_shortlink', 'st_get_shortlink', 10, 3 );

This function hooks into WordPress’ get_shortlink function and changes the native shortlink structure to the one we set everywhere on the site.

With the code in place, if you check your post’s source now, you should see the new URL structure.

Display Custom Short Link on Post

To display the link anywhere on your blog, use this code:

<?php echo wp_get_shortlink(get_the_ID()); ?>

It should be inside the loop to work.

via Christopher on GitHub