Getting the permalink for the current post in WordPress with get_the_permalink

The get_the_permalink function in WordPress is used to retrieve the permalink of the current post within the loop. This function can be useful for dynamically generating links to the current post, such as for creating custom navigation or displaying related posts. It allows developers to easily access the permanent URL of the current post without having to manually construct the permalink.

Parameters Accepted by the get_the_permalink Function

The get_the_permalink function accepts the following parameters:

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

Value Returned by the get_the_permalink Function

The get_the_permalink function returns a string or false. The permalink URL is returned as a string, while false is returned if the post does not exist.

Examples

How to get the permalink of the current post

Use the get_the_permalink function to retrieve the permalink of the current post.

<?php
$permalink = get_the_permalink();
echo $permalink;
?>

How to get the permalink of a specific post by post ID

Use the get_the_permalink function to retrieve the permalink of a specific post by its post ID.

<?php
$post_id = 123;
$permalink = get_the_permalink($post_id);
echo $permalink;
?>

How to get the permalink of a specific post within a loop

Use the get_the_permalink function within a loop to retrieve the permalink of each post.

<?php
if ( have_posts() ) {
 while ( have_posts() ) {
 the_post();
 $permalink = get_the_permalink();
 echo $permalink;
 }
}
?>

Conclusion

The get_the_permalink function is a valuable tool for developers working with WordPress. It provides a simple and efficient way to retrieve the permalink for a post or page, allowing for easy integration into custom templates or plugin development. By understanding the parameters and potential use cases for this function, developers can enhance the functionality and user experience of their WordPress websites. With its flexibility and ease of use, get_the_permalink is a valuable addition to any developer’s toolkit.