15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
10.10.2024

How to Generate a Shortlink in WordPress: A Complete Technical Guide

WordPress shortlinks are abbreviated URLs that redirect to a specific post, page, or custom post type on your site. They follow the format https://yourdomain.com/?p=POST_ID and are generated natively by WordPress using its built-in permalink rewrite system β€” no external service required.

This guide explains every method for generating, customizing, and tracking WordPress shortlinks, including native editor workflows, WP-CLI commands, plugin-based solutions, and server-level redirect behavior. Whether you are running a lean shared environment or a fully managed VPS Hosting setup, the techniques below apply directly.

WordPress generates a shortlink for every piece of content at the moment it is saved as a draft or published. The shortlink is constructed from the query string parameter ?p= followed by the post's internal database ID. This ID is assigned sequentially by the wp_posts table in MySQL or MariaDB and never changes, even if you later alter the post slug or permalink structure.

When a visitor accesses a shortlink, WordPress's index.php bootstrap loads, the rewrite engine parses the query string, and the request is internally redirected to the canonical permalink using an HTTP 301 Moved Permanently response. This means shortlinks are SEO-safe β€” search engines follow the 301 and attribute all link equity to the canonical URL.

Key technical facts:

  • Shortlinks are resolved entirely at the PHP/WordPress application layer, not at the web server level.
  • The ?p= parameter works regardless of your permalink structure setting.
  • Changing a post's slug does not break its shortlink.
  • Deleting and re-creating a post assigns a new ID, which invalidates the old shortlink.

The Classic Editor exposes a dedicated Get Shortlink button directly in the publish meta box, positioned above the post editor area.

Step-by-step:

  1. Open or create a post in the Classic Editor.
  2. Save the post as a draft or publish it β€” the shortlink cannot be generated for unsaved content because no post ID exists yet.
  3. Click Get Shortlink in the publish meta box. A modal dialog displays the shortlink URL.
  4. Copy the URL from the dialog field.

If the Get Shortlink button is not visible, it may have been hidden via Screen Options. Click the Screen Options tab at the top-right of the editor screen and ensure the Slug or shortlink-related option is checked. Some themes and plugins also dequeue this UI element via remove_action('admin_head', 'wp_shortlink_header') or filter pre_get_shortlink to return an empty string.

The Gutenberg editor removed the dedicated shortlink button from the default UI. However, the shortlink still exists and is accessible through two approaches.

Approach A β€” Manual construction from the post ID:

  1. Open the post in the Gutenberg editor.
  2. Look at the browser's address bar. The URL will contain post=XXXX where XXXX is the numeric post ID.
  3. Construct the shortlink manually:
https://yourdomain.com/?p=XXXX

Replace XXXX with the actual post ID.

Approach B β€” Post Settings sidebar:

  1. Open the post in Gutenberg.
  2. In the right-hand Post settings panel, expand the Permalink section.
  3. The post ID is visible in the editor URL. Some configurations also display the shortlink in the Summary panel if a compatible plugin is active.

Approach C β€” Restore the shortlink button via a code snippet:

If you want the shortlink button back in Gutenberg, add the following to your theme's functions.php or a site-specific plugin:

add_filter( 'get_shortlink', function( $shortlink, $id, $context, $allow_slugs ) {
    return home_url( '/?p=' . $id );
}, 10, 4 );

This filter ensures wp_get_shortlink() always returns a value, which re-enables the shortlink display in compatible UI components.

For administrators managing WordPress at the command line β€” particularly on a VPS with cPanel or a bare Dedicated Server β€” WP-CLI provides a direct way to retrieve shortlinks without touching the dashboard.

Retrieve the shortlink for a specific post by ID:

wp post get 42 --field=url --path=/var/www/html

List all published posts with their IDs and shortlinks:

wp post list --post_status=publish --fields=ID,post_title,post_name --format=table

Once you have the ID, the shortlink is simply https://yourdomain.com/?p=ID. You can also call the WordPress function directly via WP-CLI eval:

wp eval 'echo wp_get_shortlink(42);'

This outputs the shortlink string exactly as WordPress would serve it, respecting any active filters.

Native WordPress shortlinks use the ?p=ID format, which is functional but not memorable or brandable. Plugins extend this capability significantly.

Pretty Links is the most widely deployed shortlink plugin in the WordPress ecosystem. It stores custom redirects in a dedicated database table (wp_pretty_link and wp_pretty_link_clicks) and provides click tracking, geolocation data, and UTM parameter injection.

Configuration workflow:

  1. Install and activate Pretty Links from the WordPress plugin repository.
  2. Navigate to Pretty Links > Add New Link.
  3. Enter the target URL (your post's canonical permalink).
  4. Define a custom slug, for example go/my-post.
  5. Select redirect type: 301 for permanent, 302 for temporary, or 307 for temporary with method preservation.
  6. Save. The shortlink becomes https://yourdomain.com/go/my-post.

Technical note: Pretty Links rewrites are handled at the WordPress application layer via add_rewrite_rule(), not at the Apache or Nginx level. This means every shortlink hit incurs a full WordPress bootstrap. On high-traffic sites, this can add 50–200ms of latency per redirect compared to a server-level RewriteRule. If redirect performance is critical, consider offloading high-volume links to Nginx map directives or a dedicated redirect microservice.

ThirstyAffiliates

For affiliate marketers, ThirstyAffiliates provides shortlinks with click cloaking, automatic keyword linking, and geolocation-based redirect rules. It stores links in custom post types (thirstylink) rather than a separate table, making it compatible with standard WordPress backup and migration workflows.

Redirection Plugin

The Redirection plugin manages both shortlinks and general 301/302 redirects from a single interface. It also captures 404 errors and suggests redirect targets, which is valuable during site migrations.

MethodCustom SlugClick TrackingRequires PluginPerformance ImpactBest Use Case
Native `?p=ID`NoNoNoMinimalQuick internal sharing
Classic Editor buttonNoNoNoMinimalLegacy workflow
WP-CLI `wp eval`NoNoNoNone (CLI)Bulk operations, scripting
Pretty LinksYesYesYesModerate (PHP layer)Branded links, marketing
ThirstyAffiliatesYesYes (advanced)YesModerate (PHP layer)Affiliate link management
Redirection pluginYesBasicYesModerate (PHP layer)Site migrations, 404 handling
Nginx `map` directiveYesNo (external tool)NoNear-zeroHigh-traffic redirect offloading

On shared hosting, every shortlink redirect passes through the full WordPress stack: PHP-FPM or mod_php initializes, wp-config.php loads, the database connection opens, and the rewrite engine resolves the query. For low-to-moderate traffic, this is entirely acceptable.

On high-traffic sites or when running thousands of tracked shortlinks, the database query load from click logging can become a bottleneck. Practical mitigations include:

  • Object caching: Install Redis or Memcached and configure WP_CACHE in wp-config.php. This caches the redirect target lookup and reduces database reads significantly.
  • Asynchronous click logging: Configure Pretty Links to log clicks asynchronously using a background process rather than blocking the redirect response.
  • CDN-level redirects: If you use Cloudflare, you can implement bulk redirect rules at the edge, completely bypassing WordPress for high-volume links.
  • Nginx map blocks: For server-administered environments, define redirect maps directly in the Nginx configuration:
map $request_uri $redirect_target {
    /go/my-post https://yourdomain.com/full-canonical-url/;
    /go/another  https://yourdomain.com/another-post/;
}

server {
    if ($redirect_target) {
        return 301 $redirect_target;
    }
}

This approach serves redirects in microseconds without invoking PHP.

Shortlinks served over HTTP and redirecting to HTTPS targets are technically functional but expose users to a potential downgrade window. Always ensure your WordPress site has a valid SSL certificate installed so that shortlinks are served from https:// from the outset. A mixed-protocol shortlink (http://yourdomain.com/?p=42 redirecting to https://yourdomain.com/post-slug/) adds an extra redirect hop and can trigger browser security warnings in some configurations.

If you are running WordPress on AlexHost's infrastructure, pairing your site with a properly issued SSL Certificate eliminates this issue entirely and ensures all shortlinks resolve over a single, secure 301 redirect chain.

Additionally, shortlink endpoints can be abused in phishing campaigns because the destination is obscured. If you are using Pretty Links or a similar plugin, enable the noindex option on redirect pages and consider adding a rel="nofollow" attribute to externally shared shortlinks to prevent unintended crawl paths.

Retrieving the Post ID Programmatically

When building custom integrations β€” for example, generating shortlinks dynamically in a REST API response or an email template β€” use WordPress's native function:

$post_id  = get_the_ID(); // Inside The Loop
$shortlink = wp_get_shortlink( $post_id );
echo esc_url( $shortlink );

Outside The Loop, pass the post ID explicitly:

$shortlink = wp_get_shortlink( 42 );

The wp_get_shortlink() function applies the get_shortlink filter, meaning any active plugin that modifies shortlink behavior will be respected automatically. This makes it the correct function to use rather than manually concatenating home_url('/?p=') with an ID.

Use this matrix to select the appropriate method based on your operational requirements:

Use native ?p=ID shortlinks when:

  • You need a quick, no-configuration solution for internal sharing or testing.
  • You are not concerned with branded URLs or click analytics.
  • You are on a resource-constrained Shared Web Hosting plan and want zero plugin overhead.

Use Pretty Links or ThirstyAffiliates when:

  • You need branded, human-readable short slugs.
  • Click tracking, UTM parameters, or conversion attribution are required.
  • You are running a content marketing operation or affiliate site.

Use Nginx map directives or Cloudflare redirect rules when:

  • Redirect volume exceeds tens of thousands of hits per day.
  • You need sub-millisecond redirect latency without PHP overhead.
  • You are managing infrastructure directly on a Dedicated Server or high-performance VPS.

Use WP-CLI when:

  • You are scripting bulk post operations or migrations.
  • You need to retrieve shortlinks programmatically without a browser session.

Technical Key Takeaways

  • Every WordPress post has a permanent shortlink at /?p=POST_ID from the moment it is first saved; this ID never changes unless the post is deleted and recreated.
  • The Gutenberg editor removed the shortlink UI button but did not remove shortlink functionality β€” the wp_get_shortlink() function and ?p= parameter remain fully operational.
  • Plugin-based shortlinks (Pretty Links, ThirstyAffiliates) operate at the PHP application layer; for high-traffic scenarios, offload redirects to Nginx or a CDN edge rule.
  • Always serve shortlinks over HTTPS to avoid multi-hop redirect chains and potential security warnings.
  • Use wp_get_shortlink() in custom code rather than manually constructing the URL, so active plugin filters are respected.
  • Asynchronous click logging and Redis object caching are the two highest-impact optimizations for sites with heavy shortlink traffic.
  • Audit your shortlink plugin's database table growth periodically β€” wp_pretty_link_clicks can accumulate millions of rows on active sites, degrading query performance without proper indexing.

Frequently Asked Questions

Does changing a post's permalink slug break its shortlink?

No. The shortlink is tied to the post's database ID, not its slug. Changing the slug updates the canonical URL but the ?p=ID shortlink continues to resolve correctly via a 301 redirect to the new canonical permalink.

Why is the Get Shortlink button missing in my WordPress editor?

In Gutenberg, the button was removed from the default UI. It may also be hidden in the Classic Editor via Screen Options, or suppressed by a plugin using the pre_get_shortlink filter returning an empty string. Use wp eval 'echo wp_get_shortlink(POST_ID);' via WP-CLI to retrieve the shortlink regardless of UI state.

Do WordPress shortlinks affect SEO?

Native shortlinks use HTTP 301 redirects to the canonical URL, so search engines follow the redirect and attribute all ranking signals to the canonical permalink. Shortlinks themselves are not indexed. Ensure your shortlink plugin does not accidentally set redirect pages to 200 OK with thin content, which could create indexation issues.

What is the difference between a WordPress shortlink and a URL shortener like Bitly?

WordPress shortlinks are self-hosted and resolve on your own domain, preserving brand trust and keeping analytics within your infrastructure. Third-party shorteners like Bitly route traffic through an external domain, introducing a dependency on a third-party service and potentially obscuring your brand in shared links.

Can shortlinks be used in WordPress REST API responses?

Yes. Call wp_get_shortlink( $post->ID ) within a custom REST API endpoint callback or use the rest_prepare_post filter to append the shortlink field to standard post responses. This is useful for headless WordPress setups where the front-end application needs a shareable short URL without constructing it client-side.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started