The get_permalink() WordPress function

Within your WordPress theme or plugin, you may need to obtain the post permalink. In this article, we will introduce you to the get_permalink() function which you may use to obtain the permalink of either your current post or another desired post.

If you would like more information on creating WordPress plugins, see our tutorial series on creating your first WordPress plugin.

Basic usage

<?php $permalink = get_permalink( $id ); ?>

This this example, we are simply getting the post permalink from a desired post using the $id parameter, and assigning it to the $permalink variable.

Parameters

$id: This optional parameter allows you to manually define the ID of the post that you want to get the permalink of. This parameter takes an integer such as 5 for post ID 5.

$leavename: This optional parameter takes a true or false boolean operator. Instead of displaying the full permalink, it will display your permalink structure such as https://example.com/%postname%/.

Examples

Display the permalink of a specific post

In the following code example, we are getting the permalink of the post with ID 5, and assigning it to a variable. Then, we are displaying the contents of that variable:

<?php
$permalink = get_permalink(5);
echo $permalink;
?>

Display the permalink structure of a specific post

In this example, we are getting the permalink structure of the post with ID 5 and assigning it to a new variable. Then, we are displaying that permalink structure:

<?php
$permalink = get_permalink(5, true);
echo $permalink;
?>

References

For more information on the get_permalink() WordPress function, take a look at the get_permalink() WordPress Codex page.

Comments

It looks like this article doesn't have any comments yet - you can be the first. If you have any comments or questions, start the conversation!

Was this article helpful? Let us know!