wordpress

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().

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


Solution

  • <!--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;
    ?>