Getting the permalink of a specific page in WordPress using get_page_link
The get_page_link
function in WordPress is used to retrieve the permalink of a specific page based on its ID. This can be useful when you need to dynamically generate links to specific pages within your WordPress website, such as in a custom navigation menu or within a template file.
By using the get_page_link
function, you can ensure that the links you generate will always point to the correct page, even if the permalink structure of your website changes or if the page is moved to a different location within the site hierarchy.
Parameters Accepted by the get_page_link Function
The get_page_link
function accepts the following parameters:
$post
(intWP_Post), optional. Default value: false. Description: Post ID or object. Default uses the global$post
.$leavename
(bool), optional. Default value: false. Description: Whether to keep the page name.$sample
(bool), optional. Default value: false. Description: Whether it should be treated as a sample permalink.
Value Returned by the get_page_link Function
The get_page_link
function returns a string, which is the page permalink.
Examples
How to get the permalink of a specific page by ID
$page_id = 5;
$permalink = get_page_link($page_id);
echo $permalink;
This code snippet retrieves the permalink of a specific page with ID 5 using the get_page_link
function and then echoes the permalink.
How to get the permalink of the current page
$current_permalink = get_page_link();
echo $current_permalink;
This code snippet retrieves the permalink of the current page using the get_page_link
function and then echoes the permalink.
How to conditionally get the permalink based on the page’s parent
$parent_id = wp_get_post_parent_id(get_the_ID());
if ($parent_id) {
$parent_permalink = get_page_link($parent_id);
echo $parent_permalink;
} else {
echo "No parent page found";
}
This code snippet first gets the parent ID of the current page using wp_get_post_parent_id
, then uses get_page_link
to retrieve the parent page’s permalink. It then checks if a parent page exists and echoes the parent permalink, or else it echoes a message indicating no parent page was found.
Conclusion
The get_page_link
function is a valuable tool for WordPress developers looking to easily retrieve the URL of a specific page within their website. By providing the page ID as a parameter, this function simplifies the process of generating page links, making it easier to create dynamic and user-friendly websites. Additionally, the get_page_link
function offers flexibility by allowing developers to customize the link using the optional $leavename
parameter.
Whether you are building a simple blog or a complex e-commerce site, the get_page_link
function can streamline your development process and improve the overall user experience. By incorporating this function into your WordPress projects, you can ensure that your website’s links are accurate, consistent, and easy to manage.