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()
.
The get_permalink()
Function
The 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:-
1 | <?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.
Using 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:-
1 | <?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!
Comments
Polite Disclaimer: I am welcome, open and willing for corrections to be shared in the comments (with corrections being added to posts and credited), and the comments field should be used to promote discussion and make this post better. I do not know everything and if anybody finds a better way to do something, then by all means please share it below.
However, I'm unable to offer support to posts. The reason being is that WordPress has tens of thousands of plugins and millions of themes. As such, finding out exactly why code doesn't work with your setup is a long process. If you wish for me to look at your code, please use the priority support area.
Comments asking support will be left on the site, but there is no guarantee of answer.
Comments are closed.