Home / functions.php / Get the page ID by the page name
  • How to Get the page ID by the page name

    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.

    wordpress snippet : PHP - functions.php

    <>
    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;
    }
    

    wordpress snippet : PHP - template

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

    ( WordPress codex functions, hooks, in this snippet. )

    template, _n, wp,
  • stvwlf

    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;
        }
    }

     

  • http://wpsnipp.com Kevin Chard

    Cool this will be very useful to people.

  • Gabriel Merovingi

    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;
    }

    • http://wpsnipp.com Kevin Chard

      Slick Gabriel,

  • http://twitter.com/Jtsternberg Justin

    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;}

    • Gabriel Merovingi

      You are correct Justin. 

  • disqus_xTrza4CMqz

    not working

  • disqus_xTrza4CMqz

    not working

    • http://wpsnipp.com Kevin Chard

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