Get ID from Page Name

Add to functions.php file:

function 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."' AND post_type = 'page'");
   return $page_name_id;
}

Now you can use this function in templates when you need an ID of a specific post/page and all you have is the name.

Comments

  1. User Avatar
    Cmet
    Permalink to comment#

    dont forget escaping for security, especially if you don’t have full control over the use and input of this function.

    mysql_real_escape for instance,

  2. User Avatar
    Aldo
    Permalink to comment#

    There is already a function in the WordPress core to make this:

    get_page_by_title( $page_title, $output, $post_type );

    http://codex.wordpress.org/Function_Reference/get_page_by_title

  3. User Avatar
    Silvana
    Permalink to comment#

    Sorry but get_page_by_title searches for title and not for name

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag