How to get page’s ID if I know the title only?

Is there an exact opposite funciton to this one:

get_the_title(ID) 

I know there’s:

Read More
get_the_id()

But it doesn’t seem to accept any arguments.

So, basically, I’m looking for something like:

$title = 'Something';
get_the_id($title);

I already know this solution:

 global $wpdb;
 $post_name = get_query_var('name');
 $post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $post_name");

But maybe there’s something bulit-in that I’m missing?

Related posts

Leave a Reply

4 comments

  1. get_page_by_title( $title, [$output = 'object'], [$post_type = 'page'] ) exists for this very purpose. I’m using it in one of my projects now to display all attachments for a particular page in my sidebar:

    if ( $oPage = get_page_by_title('Proudly Supporting...') ) {
    
      $children = get_posts(array(
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'numberposts'    => 3,
        'post_status'    => null,
        'post_parent'    => $oPage->ID, /* Using the Page ID */
        'orderby'        => 'rand',
      ));
    
      if ( $children ) {
        /* Do something with the children */
      }
    
    }
    
  2. I had the same problem. I used the next code:

    $my_title = 'My title';
    global $wpdb;
    $mypost = $wpdb->get_row( "SELECT * FROM wp_posts WHERE post_title = '" . $my_title . "' " );
    echo $mypost->ID;