Wordpress : Get page permalink by name, slug or title outside loop

It's only fair to share...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponEmail this to someone

I know we have get_permalink() in WordPress to get permalink by id of specific page. So this post is only alternative how to get the permalink by name, slug or title.

1. Get Page ID by name, slug or title

[php]
<?php
function rh_get_page_id($name)
{
global $wpdb;
// get page id using custom query
$page_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE ( post_name = ‘".$name."’ or post_title = ‘".$name."’ ) and post_status = ‘publish’ and post_type=’page’ ");
return $page_id;
}
?>
[/php]

2. Get Page Permalink by name, slug or title

[php]
<?php
function rh_get_page_permalink($name)
{
$page_id = rh_get_pageid($name);
return get_permalink($page_id);
}
?>
[/php]

3. How To Use

[php]
<?php
// get by title
echo rh_get_page_permalink(‘Your Page Name’);
// get by name or slug
echo rh_get_page_permalink(‘your-page-name’);
?>
[/php]

Enjoy.. I hope it useful and works for you 🙂

http://codex.wordpress.org/Function_Reference/get_permalinkget
It's only fair to share...Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on StumbleUponEmail this to someone
  • Moreopenasia

    where can i place the code for permalink with : pagename or by postname? please help

  •  you can place everywhere you want as long as you know your page name/slug

  • Moreopenasia

    sorry i dint understand…. should i place them in CSS ….?

  • I mean you can put in your active theme.. in php file of course

  • Moreopenasia

    thank you for the help….

  • Kristjan Gomboc

    i’ve been searching for 2 days now! Big tnx for this one 😉

  • You named it function rh_get_page_id($name) but you called it as $page_id = rh_get_pageid($name);