When building themes, you occasionally need to be in a situation where you link to something within your theme that is a page or a post within your site. Ideally you want to avoid it if you can, using WordPress’ ability to position things correctly using menus, or widgets, or something within the database. However should you need to link directly in the theme, it’s not a good idea to use full URL’s, but rather a small helper function,
get_permalink() function is a helper function that has been in WordPress since the beginning What you can use it for is to get the URL of a permalink associated with any page ID or post ID. It takes a single argument usually – an integer, or a post object.
So for example, if your contact us has an ID of 2, rather than link directly to /contact-us/ in the theme, you can use this line to generate the permalink instead:-
<?php echo get_permalink(2); ?>
The reason for this is that should you ever change your domain, you don’t have to change your code, providing the database is the same.
get_permalink() & Page ID’s together
Where the power really lies is in URLs for pages, as as long as whatever you build returns a post object, you can put anything within the brackets. One of the most useful features is getting a direct link for the news page, for example:-
<?php echo get_permalink( get_option( 'page_for_posts' ) ); ?>
This will return the URL of the news page. No matter if you change the URL, or the option within the database.
There are other options – to use, for example, WooCommerce ID’s of account pages, should you use WooCommerce pages, but this function is rather powerful, so well worth hunting out.
How about you? Do you have any other examples? Please leave them in the comments below!