Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get wordpress post by post title

Tags:

php

wordpress

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?

like image 887
user2710234 Avatar asked Jan 10 '14 09:01

user2710234


2 Answers

try this

$post_title = 'Contact';
$post_id = get_page_by_title($post_title, OBJECT, 'your_post_type_name');
echo $post_id->ID; // your id
like image 154
Andrey Shandrov Avatar answered Nov 15 '22 16:11

Andrey Shandrov


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;
like image 39
Mahmood Rehman Avatar answered Nov 15 '22 17:11

Mahmood Rehman