tags:

views:

2000

answers:

2

Hi all,

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.

+3  A: 

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: http://sudarmuthu.com/blog/2009/09/18/retrieving-posts-and-pages-based-on-title-in-wordpress.html

Aaron
Just put that function in your functions.php file.
Littlejon
Note that you may wish to change post_type to 'page' if you want to get the id for a page. You can also omit the post_type from the SQL where clause to search all revisions, pages, and posts, etc. (All types in other words.)
American Yak
A: 

I think here is a directly way to get post id by title.I have tried.

feilong