Using WordPress ‘get_shortlink’ PHP filter

The get_shortlink WordPress PHP filter allows you to modify the shortlink for a post.

Usage

add_filter('get_shortlink', 'your_function_name', 10, 4);
function your_function_name($shortlink, $id, $context, $allow_slugs) {
    // your custom code here
    return $shortlink;
}

Parameters

  • $shortlink (string) – Shortlink URL.
  • $id (int) – Post ID, or 0 for the current post.
  • $context (string) – The context for the link. One of ‘post’ or ‘query’.
  • $allow_slugs (bool) – Whether to allow post slugs in the shortlink. Not used by default.

More information

See WordPress Developer Resources: get_shortlink

Examples

Modify the shortlink by changing the domain.

function change_shortlink_domain($shortlink, $id, $context, $allow_slugs) {
    $shortlink = str_replace('example.com', 'newdomain.com', $shortlink);
    return $shortlink;
}
add_filter('get_shortlink', 'change_shortlink_domain', 10, 4);

Add UTM parameters to the shortlink for tracking purposes.

function add_utm_parameters($shortlink, $id, $context, $allow_slugs) {
    $shortlink .= '?utm_source=example&utm_medium=referral&utm_campaign=share';
    return $shortlink;
}
add_filter('get_shortlink', 'add_utm_parameters', 10, 4);

Remove any query parameters from the shortlink.

function remove_query_parameters($shortlink, $id, $context, $allow_slugs) {
    $shortlink = strtok($shortlink, '?');
    return $shortlink;
}
add_filter('get_shortlink', 'remove_query_parameters', 10, 4);

Use post slug in shortlink

Include the post slug in the shortlink.

function use_slug_in_shortlink($shortlink, $id, $context, $allow_slugs) {
    $post = get_post($id);
    $slug = $post->post_name;
    $shortlink .= '/' . $slug;
    return $shortlink;
}
add_filter('get_shortlink', 'use_slug_in_shortlink', 10, 4);

Disable shortlink for specific post types

Disable shortlink generation for specific post types.

function disable_shortlink_for_post_type($shortlink, $id, $context, $allow_slugs) {
    $post = get_post($id);
    if ($post->post_type == 'custom_post_type') {
        return false;
    }
    return $shortlink;
}
add_filter('get_shortlink', 'disable_shortlink_for_post_type', 10, 4);