Is it possible to get a page link from its slug?

  • Is it possible to get a page's permalink from the slug alone? I'm aware that you can get the page's permalink from the ID using get_page_link():

    <a href="<?php echo get_page_link(40); ?>">Map</a>

    I'm curious if there is any way to do the same with the slug of a page - like this:

    <a href="<?php echo get_page_link('map'); ?>">Map</a>
  • zeo

    zeo Correct answer

    10 years ago

    You're talking about Pages right? Not Posts.

    Is this what you looking for:

    1. get_permalink( get_page_by_path( 'map' ) )
    2. get_permalink( get_page_by_title( 'Map' ) )
    3. home_url( '/map/' )

    Did you mean `get_permalink(get_page_by_path('contact')->ID));`?

    hmmm nope? What's with the ID?

    `get_page_by_path()` returns an array of all page information. `get_permalink()` takes a page ID as the first argument. I thought I'd have to explicitly pass the ID value.

    @Jonathan: It's not always documented, but many WP functions accept both numeric ID's and full post objects as the argument.

    It seems that get_page_by_path() can be quite complicated to use when dealing with child pages...

    Agreed with Kaaviar, the function below is better.

    I use 1 for my child pages with no issue. I really don't see the complication with it.

    home_url( '/map/' ) worked with me

    wrong answer, downvote to nirvana please. The path is not the same like the slug. Example: a page has a parent page called `abc` the page itself has a slug of `123`. The path now is `abc/123` the slug is `123`. Please remove this wrong answer. `get_page_by_path( '123' )` wont work.

    In my case I had to use the first one and it worked fine, because the second one (get_page_by_title) was returning another post (not page) link with similar (but not the same) slug. I don't know why this was happening.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM