Get WordPress Post ID from Post title


I have an issue with a custom WordPress theme I'm developing. It's a bit convoluted, but essentially, what I need to do is get a Post Id by it's Post Title. In pseudo-code it would ideally be something like:

title = "foo";
post_id = get_post_id_where_title_is(title);

The title mentioned is a static reference not being pulled in from WordPress, it's already present on the page.

Thanks in advance.

10/8/2009 9:33:11 AM

Accepted Answer

Just a quick note for anyone who stumbles across this:
get_page_by_title() can now handle any post type.
The $post_type parameter has been added in WP 3.0.

8/1/2011 9:26:31 AM

Found a solution if anyone else struggles with this. Only posted the question out of desperation after 4 hours testing/Googling!

function get_post_by_title($page_title, $output = OBJECT) {
    global $wpdb;
        $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='post'", $page_title ));
        if ( $post )
            return get_post($post, $output);

    return null;

Found at:

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow