If you’re used to working with The Loop, then you’re all too familiar with the_permalink. Simply put, it’s how to get the link to the post currently being rendered in the browser.
But if you’re working on anything more advanced than using the typical Loop, then you may be looking to get the permalink for a post by other means – perhaps by a page slug or by a page’s title.
I’ve had to do this in some recent work, as well, so here’s what I do when I need to get permalink by slug:
Get Permalink By Slug
If you’re looking to get the permalink by the slug, then you need to know two things:
- A page’s slug is usually the post name unless you’ve done something else programmatically. Review this Codex article for more information.
- The get_permalink function can accept an ID or an actual object. I’m a fan of passing the ID. I think it makes for cleaner code when comparing it to the Codex documentation.
So with that said, let’s assume that there’s a page that has the slug: “Register For This Site.” Since the slug is often the page’s title, we can write the following function:
01 | function theme_get_permalink_by_title( $title ) { |
07 | $page = get_page_by_title( strtolower ( $title ) ); |
11 | $permalink = get_permalink( $page ->ID ); |
You can then interact with this function by doing the following. Remember “Register For This Site” is the name of the page:
1 | if ( null == theme_get_permalink_by_title( 'Register For This Site' ) ) { |
Although we’re technically getting the page’s permalink by its slug, the slug is often synoymous with the page’s title so I tend to prefer to write my functions so they are a bit more readable – title seems to be a bit clearer than slug.
Notice also that I’m performing a strtolower
within the theme_get_permalink_by_title
function. WordPress will handle the case when it’s lowercase and I always find it a best practice to normalize whatever input the user has provided given the function.
Leave a Reply
You must be logged in to post a comment.