WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am trying to create a function for my functions.php file that will allow me to convert a post name into a post id. I have had a look around online and managed to find this link http://www.devdevote.com/cms/wordpress-hacks/get_id_by_post_name which gives the following example..

function get_id_by_post_name($post_name)
    global $wpdb;
    $id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$post_name."'");
    return $id;

<?php echo get_id_by_post_name('my-post-name'); ?>

After replacing my-post-name in the example I am not getting any results, can anyone suggest what is wrong?

I was also looking into the get_by_postname function in case this was a better way of doing things.

share|improve this question
up vote 2 down vote accepted

Use get_page_by_title(). It works with any post type.

$post = get_page_by_title( $post_name, OBJECT, 'post' );
echo $post->ID;
share|improve this answer
Thanks toscho, that was exactly what I was looking for :) – fightstarr20 Jul 19 '12 at 15:57
I am now trying to move on with this function and convert it so that it uses the post name instead of the Id. I have created a new question at wordpress.stackexchange.com/questions/59050/… - Any chance you could look in? – fightstarr20 Jul 19 '12 at 16:21

It looks to me like get_page_by_path() is the function you'd use to do a lookup by post_name (or a slash separated hierarchy of them), and get_page_by_title() would work only for post_title.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.