Wordpress - Is it possible to get a page link from its slug?
You're talking about Pages right? Not Posts.
Is this what you looking for:
get_permalink( get_page_by_path( 'map' ) )
get_permalink( get_page_by_title( 'Map' ) )
home_url( '/map/' )
I think this could be better:
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
$page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s", $page_slug, $post_type ) );
if ( $page )
return get_page($page, $output);
return null;
}
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:
/**
* Returns the permalink for a page based on the incoming slug.
*
* @param string $slug The slug of the page to which we're going to link.
* @return string The permalink of the page
* @since 1.0
*/
function wpse_4999_get_permalink_by_slug( $slug, $post_type = '' ) {
// Initialize the permalink value
$permalink = null;
// Build the arguments for WP_Query
$args = array(
'name' => $slug,
'max_num_posts' => 1
);
// If the optional argument is set, add it to the arguments array
if( '' != $post_type ) {
$args = array_merge( $args, array( 'post_type' => $post_type ) );
}
// Run the query (and reset it)
$query = new WP_Query( $args );
if( $query->have_posts() ) {
$query->the_post();
$permalink = get_permalink( get_the_ID() );
wp_reset_postdata();
}
return $permalink;
}
It works with custom post types and built-in post types (such as post
and page
).