How can I get a post by title in WordPress?

WordPress 3.0

I want to have the contents of a specific post into a page by using the title of the post. As far as I can tell, I can’t do it directly with get_post().

Read More

I can assume what the brute force way might be, but I suspect there’s a more elegant way?

Related posts

Leave a Reply

6 comments

  1. <!--1.Get post ID by post title if you know the title or the title variable-->
    <?php
    $posttitle = 'post_title';
    $postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
    echo $postid;
    ?>
    
    <!--2.use get_post($post_id) to get whatever you want to echo-->
    <?php
    $getpost= get_post($postid);
    $postcontent= $getpost->post_content;
    echo $postcontent;
    ?>
    
  2. You can use this:

    1)

    global $wpdb;
    $your_title = "yourtitle";
    $id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $your_title");
    echo $id;
    

    or 2)

        $slug_to_get = 'my_title_or_slug';
        // you can use custom post type too
        $posttypee='post';
    
        $args=array(
          'title' => $slug_to_get,
          'post_type' => $posttypee,
          'post_status' => 'publish'
          );
        $my_posts = get_posts($args);
        if( $my_posts ) {
        echo 'ID on the first post found '.$my_posts[0]->ID;
        }