Using WordPress ‘get_permalink()’ PHP function

The get_permalink() WordPress PHP function retrieves the full permalink for the current post or post ID.

Usage

$permalink = get_permalink( $post, $leavename );
// your custom code here
return $permalink;

Parameters

  • $post int|WP_Post (Optional) – Post ID or post object. Default is the global $post.
  • $leavename bool (Optional) – Whether to keep post name or page name. Default: false

More information

See WordPress Developer Resources: get_permalink()

Examples

Display Permalink for Current Post

This code displays the permalink for the current post within The Loop.

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        echo get_permalink();
    }
}

Retrieve Permalink for a Specific Post

This code retrieves the permalink for a specific post by its ID.

$post_id = 42; // Replace 42 with your desired post ID
$permalink = get_permalink( $post_id );
echo $permalink;

Retrieve Permalink for a Post Object

This code retrieves the permalink for a post using a WP_Post object.

$post_object = get_post( 42 ); // Replace 42 with your desired post ID
$permalink = get_permalink( $post_object );
echo $permalink;

Retrieve Permalink with Post Name

This code retrieves the permalink for a post, keeping the post name in the URL.

$permalink = get_permalink( 42, true ); // Replace 42 with your desired post ID
echo $permalink;

This code displays the permalink as a link, using the post title as the link text.

if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
    }
}

Redirect to a page with page ID

wp_redirect( get_permalink(1443) );
exit;