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.
<?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.
$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%/.
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:
$permalink = get_permalink(5);
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:
$permalink = get_permalink(5, true);
For more information on the get_permalink() WordPress function, take a look at the get_permalink() WordPress Codex page.