Getting the permanent link of a post or page in WordPress with get_permalink function

The get_permalink function in WordPress is used to retrieve the permalink of a specified post or page. This function can be useful when you need to dynamically generate URLs for posts or pages in your WordPress site. It allows you to easily access the permalink without hardcoding the URL, making your code more flexible and maintainable.

Parameters Accepted by get_permalink Function

The get_permalink function accepts the following parameters:

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

Value Returned by get_permalink Function

The get_permalink function returns a string representing the permalink URL. If the post does not exist, it returns false.

Examples

How to get the permalink of a post by ID

$post_id = 123;
$permalink = get_permalink( $post_id );
echo $permalink;

This code snippet retrieves the permalink of a post with the ID of 123 using the get_permalink function and then echoes the permalink.

How to get the permalink of the current post

$permalink = get_permalink();
echo $permalink;

This code snippet retrieves the permalink of the current post using the get_permalink function and then echoes the permalink.

How to get the permalink of a specific page by slug

$page_slug = 'about-us';
$page_permalink = get_permalink( get_page_by_path( $page_slug ) );
echo $page_permalink;

This code snippet retrieves the permalink of a specific page with the slug ‘about-us’ using the get_permalink function and then echoes the permalink.

Conclusion

The get_permalink function is a crucial tool for WordPress developers and website owners. It provides a simple and efficient way to retrieve the permanent link to a post or page within the WordPress environment. By using this function, developers can ensure that their links are always up-to-date and accurate, regardless of any changes made to the site’s permalink structure. Additionally, the get_permalink function is versatile and can be used in a variety of contexts, making it a valuable asset for any WordPress project. With its ability to handle different post types and custom post types, this function offers a reliable solution for generating permalinks throughout a WordPress site. Overall, the get_permalink function is an essential tool for any WordPress developer looking to streamline their workflow and improve the user experience for their website visitors.

Related WordPress Functions