wordpress
comment 0

Generate WordPress Page URL using Slug

WordPress theme developers are surely familiar with the function get_page_link($page_id) to generate page URL based on the supplied page ID. The advantage of using this function as opposed to directly hard-coding the URL is it obeys the permalink rules you have defined in WordPress. However, what if you want to identify the page using its slug instead of ID? It turns out to be quite simple, do read more.

$url = get_page_link(get_page_by_path('my-page-slug')->ID);

That’s it! This single line of code allows us to get the WordPress page URL using slug instead of ID.

But you may ask, why do I need this? Isn’t get_page_link($page_id) the same thing since we always know the page ID?

Sure, but the issue arises when you are maintaining two versions of WordPress of the same website, say a live version and a localhost version (for development). When you do all the cool PHP stuff in the localhost version especially involving adding new Pages with custom functionalities, it is almost impossible to expect an identical Page ID when you create a new page in the live server. That means your calls to get_page_link($page_id) would produce wrong URLs. On the other hand, the page slugs we can control :)

Leave a Reply