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>
Is this what you are looking for:
get_permalink( get_page_by_path( 'map' ) )
get_permalink( get_page_by_title( 'Map' ) )
home_url( '/map/' )
References:
get_permalink
documentationget_page_by_path
documentationget_page_by_title
documentationhome_url
documentationI think this could be better:
following the pattern of “original”
get_page_by_title
of wordpress. (line 3173)rgds
This is a method published by Tom McFarlin on his blog:
It works with custom post types and built-in post types (such as
post
andpage
).the accepted answer is wrong because hierarchical pages don’t work like that. Simply put, the slug is not always the path of the page or post. E.g. your page has a child etc. the path will be
parent-slug/child-slug
andget_page_by_path
will fail to findchild-slug
this way. The proper solution is this:Try This:
get_page_by_path( 'path' )
returns page/post object which can be then used byget_page_link()
as it accepts post/page object and returns permalink.Use this function by
A little late, but kind of…
You can do this:
<?php $map = get_page_by_title( 'map' ); ?>
<a href="<?php echo get_page_link('$map->ID'); ?>">Map</a>
That’s how I do it 🙂
Thanks,
Josh