飞龙博客

feilong.org 前端开发教程

wordpress Get post ID by post title

飞龙修订于 20070616 02:46 19 次浏览

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

想学前端?长按二维码加我微信

想学前端?点击飞龙QQ

分类: wordpress

新作:

旧文:

关闭

长按二维码 -> 识别图中二维码

打开微信,发现,扫一扫

支付完成后,点击下一步

感谢大力支持

然后你手机号:

最后点这,稍等即可