WordPress: Get Page Link By Slug

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, 2009
Tags: , ,

11 Responses to “WordPress: Get Page Link By Slug”

  1. zz says:

    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?

  2. Andrew Boldman says:

    I have been wondering about this wordpress issue, so thanks for posting a solution.

  3. StrangeAttractor says:

    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…

  4. The only thing I’m bewildered by is that this isn’t part of core! Thanks for the quick solution.

  5. emonweb says:

    you know im thinking the same way as you? i would like to keep my wordpress theme id less.

  6. Hassan says:

    Thanks, It worked on my website. It will be soon online.

  7. clooney says:

    Awesome! Works perfectly. Thank you very much. Its strange that such a function is not part of the WordPress API.

Leave a Reply