user2710234
user2710234

Reputation: 3225

Get WordPress post by post title

I am using this code to show WordPress posts in an external website:

<?php
    require('wp_blog/wp-blog-header.php');
    
    if($_GET["p"] > '') { ?>
    
    <?php query_posts('p='.$_GET["p"].''); ?>
    <?php while (have_posts()) : the_post(); ?>
        <h4><?php the_title(); ?></h4>
        <?php the_content(); ?>
    <?php endwhile; ?>
    <?php } else { ?>
    
    <?php
    $posts = get_posts('numberposts=10&order=ASC&orderby=post_title');
    foreach ($posts as $post) : setup_postdata( $post ); ?>
        <?php the_date(); echo "<br />"; ?>
        <?php the_title(); ?>    
        <?php the_excerpt(); ?> 
    <?php endforeach; ?>
    
    <?php } ?>

Rather than selecting the post based on the ID, how can I make it select the post based on the post title?

Upvotes: 16

Views: 59056

Answers (4)

Alexander Z
Alexander Z

Reputation: 604

Function get_page_by_title() is deprecated. This is another simple function for this issue:

function get_post_id_by_title( $title, $post_type ) {
    global $wpdb;
    return $wpdb->get_results("SELECT ID FROM wp_posts where post_type='".$post_type."' AND post_title='".$title."'");
}

Upvotes: 1

Andrey Shandrov
Andrey Shandrov

Reputation: 457

try this

$post_title = 'Contact';
$post_id = get_page_by_title($post_title, OBJECT, 'your_post_type_name');
echo $post_id->ID; // your id

Upvotes: 7

Anjana
Anjana

Reputation: 499

Add Function Like this

function get_page_by_post_name($post_name, $output = OBJECT, $post_type = 'post' ){
    global $wpdb;
    $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $post_name, $post_type ) );

    if ( $page ) return get_post( $page, $output );

    return null;
}

 add_action('init','get_page_by_post_name');

And run like that:

 $page = get_page_by_post_name('hello-world', OBJECT, 'post');
 echo $page->ID; 

Upvotes: 2

Mahmood Rehman
Mahmood Rehman

Reputation: 4331

You can use get_page_by_title() to fetch post by title.Like this:

$page = get_page_by_title('About', OBJECT, 'post');
echo $page->ID

Details are here.

OR custom query like this :

$posttitle = 'About';
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
echo $postid;

Upvotes: 40

Related Questions