X

Get the page ID by the page name

Add the first snippet into the functions.php and the second snippet into one of your wordpress template files. This snippet will allow you to return a page ID by the page name. Don't forget to change PAGE_NAME to the name of the page you would like to return the ID of.



Code Snippet:


function wds_get_ID_by_page_name($page_name)
{
global $wpdb;
$page_name_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name ='".$page_name."'");
return $page_name_id;
}


Code Snippet:


<?
$the_page_id = wds_get_ID_by_page_name('PAGE_NAME');
echo $the_page_id;
?>

Comments  Leave a Reply

  1. disqus_xTrza4CMqz March 28, 2014 at 7:17 am

    not working

    1. Need more info before we can help out! What problems are you running into, any errors or more details you can provide?

  2. disqus_xTrza4CMqz March 28, 2014 at 7:17 am

    not working

  3. hmmm… the WP function function get_page_by_title is very close to this function… This function is just more selective. (get only the id), and allows getting any post_type by name.  Probably best to use the WordPress function though.
    get_page_by_title($page_title, $output = OBJECT, $post_type = ‘page’ ) { global $wpdb; $page = $wpdb->get_var( $wpdb->prepare( “SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s”, $page_title, $post_type ) ); if ( $page ) return get_page($page, $output); return null;}

    1. Gabriel Merovingi July 30, 2011 at 1:48 pm

      You are correct Justin. 

  4. Gabriel Merovingi July 21, 2011 at 7:51 pm

    You can also get the same result by using get_page_by_title() function:

    function get_page_id_by_title( $title )
    {
    $page = get_page_by_title( $title );
    return $page->ID;
    }

    1. Slick Gabriel,

  5. Cool this will be very useful to people.

  6. Hi – I used to do it the way you are suggesting, with custom SQL. But later found there is a built in WP function.

    function wds_get_ID_from_slug($slug) {
       $page = get_page_by_path($slug);
       if ($page) {
             return $page->ID;
       } else {
            return 0;
        }
    }

     

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!