飞龙博客

妙法莲华经

wordpress Get post ID by post title

feilong.org 修订于2007-06-16 02:46:37

Feilong want to get post id by title,but there is none template tags (get_post_by_title)directly to realize it. If you know a post id ,you can get the post title or content  or slug very easily by using get_post($post_id).Still,if you want to Get page ID by title,you can use get_page_by_title.

BUT if you want to get the post id by title?When you have get or know the post title,how to get the post id?Here feilong code below for you to test in sidebar.php of your template.This post's modified url is http://feilong.org/wordpress-get-post-id-by-post-title

Firstly  Get post ID by post title through querying the wordpress database,then you can use get_post($post_id) to get whatever you want to echo.

<!--1.Get post ID by post title if you know the title or the title variable-->
<?php
$posttitle = 'Hello world!';
$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;
?>

BUT in order to let myself and you my friends to understand how to query the database,I code two more samples just the same way as step 1.

<!--Get post slug name by post title -->
<?php
$posttitle = 'Hello world!';
$post_slug_name = $wpdb->get_var( "SELECT post_name FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
echo $post_slug_name;
?>
<!--Get post_content by post title -->
<?php
$posttitle = 'Hello world!';
$post_content = $wpdb->get_var( "SELECT post_content FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
echo $post_content;
?>

Thanks to get-wordpress-post-id-from-post-title

更新网址:https://feilong.org/wordpress-get-post-id-by-post-title
最初发布:20070616 02:46:37 feilong.org 于广州

加入收藏夹,查看更方便。

所在分类: wordpress

新作:

旧文: