While building the template for my website I had the need to quickly and easily generate links to WordPress pages where I knew the slug (or name) of the page, but not the ID.
Usually I would use the get_permalink(); function to generate links, but as this function requires me to know the ID of the page I want to link to, and since I wanted to use it outside the loop, where the ID isn’t always at hand I had to find an alternate way of building the URLs.
Enter, get_page_by_path().
The function get_page_by_path() returns an object with the page and all its goodies. I wrapped it all in a function and placed it in my template’s functions.php file where it can easily be re-used.
function get_page_link_by_slug($page_slug) { $page = get_page_by_path($page_slug); if ($page) : return get_permalink( $page->ID ); else : return "#"; endif; }
As far as I can see this is the easiest solution for getting the page link via the slug. I’m wish I didn’t have to drag the entire page object along to do it, but what can I say.
Some (but not much) more info on this function can be found here.
It is also possible to replace get_page_by_path() with get_page_by_title() and use the title of the page instead of the slug.
Date: May 21, 2009Tags: code, slug, wordpress



use get_pagenum_link();
get_pagenum_link(); takes as its argument an integer (ie, the ID), which isn’t always known.
One would still have to write this function about 99% the same. How would using get_pagenum_link(); improve the function?
I have been wondering about this wordpress issue, so thanks for posting a solution.
Found an interesting work-around — you can assign categorized WordPress links to your site’s actual pages, and then use a function to call up the links and the manipulate them that way…
See:
http://justintadlock.com/archives/2009/01/06/easy-navigation-menus-in-wordpress
Maybe useful in this context…
Hi StrangeAttractor
The link you posted takes me to a site that is very very broken. I’ll check back later to see if someone fixed it.
The only thing I’m bewildered by is that this isn’t part of core! Thanks for the quick solution.
I’m glad this helped.
Yeah, I totally think this should make it to the core. Oh well. *shrug*
you know im thinking the same way as you? i would like to keep my wordpress theme id less.
Thanks, It worked on my website. It will be soon online.
Awesome! Works perfectly. Thank you very much. Its strange that such a function is not part of the WordPress API.
Glad to have been able to help. I’ve also wondered why something so simple (and obviously useful) hasn’t been included in core.