Example 1 — Print the short URL
Print the short link for the current post.
<?php echo esc_url( wp_get_shortlink() ); ?> How It Works
wp_get_shortlink()returns the short URL.esc_url()makes it safe.- The number is the ID of the post.

In WordPress, wp_get_shortlink() returns the short URL of a post, such as https://example.com/?p=12. It does not print.
Use it when you want only the URL, for example to copy it or put it in a meta tag.
A few ways to call wp_get_shortlink().
<?php
echo esc_url( wp_get_shortlink() ); | Call | What it does |
|---|---|
wp_get_shortlink() | Short link of the current post. |
wp_get_shortlink( 12 ) | Short link of the post with ID 12. |
wp_get_shortlink( 12, 'post' ) | Use the post context. |
the_shortlink() | Print a full anchor tag with the short link. |
It returns the URL. Use echo esc_url() to print it.
wp_get_shortlink( int $id = 0, string $context = 'post', bool $allow_slugs = true ): string | Parameter | Description |
|---|---|
$id | int. A post ID. Default is 0, which uses the current post. |
$context | string. The kind of ID, post or query. Default is post. |
$allow_slugs | bool. Whether a plugin may replace the ID with a slug. Default is true. |
| Return Value | Description |
|---|---|
| string | The short URL. It can be an empty string if there is none. |
Three short examples. Each one shows the code and what it prints.
Print the short link for the current post.
<?php echo esc_url( wp_get_shortlink() ); ?> wp_get_shortlink() returns the short URL.esc_url() makes it safe.Pass a post ID.
<?php
$url = wp_get_shortlink( 42 );
echo 'Share: ' . esc_url( $url ); 42 is a post ID.Print a link tag in the head for tools that read it.
<?php
function mytheme_shortlink_tag() {
if ( is_singular() ) {
$url = wp_get_shortlink();
if ( $url ) {
echo '<link rel="shortlink" href="' . esc_url( $url ) . '">' . "\n";
}
}
}
add_action( 'wp_head', 'mytheme_shortlink_tag' ); wp_head hook runs in the page head.is_singular() limits the tag to single posts and pages.Open the functions index for simple guides with examples and FAQs.
12 people found this page helpful