Get WordPress Post ID from Post title
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
Like Michal Mau mentioned:
Use
$my_post = get_page_by_title( 'My Title', OBJECT, 'post' );
echo $my_post->post_content;
It's ( $page_title, $output, $post_type )
to easily receive a post instead of a page.
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.
May this will help you more by creating function so that you need not to repeat the code
function get_page_id_by_title($title)
{
$page = get_page_by_title($title);
return $page->ID;
}
$title = "your title";
get_page_id_by_title($title);