飞龙博客

feilong.org 前端开发教程

wordpress Get post ID by post title

飞龙更新于 2007-06-16 02:46 加入书签 CTRL+D 有 286 个朋友来过

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

飞龙初发:
2007-06-16 02:46
本文更新网址:
https://feilong.org/wordpress-get-post-id-by-post-title

所在目录: wordpress

新作:

旧文:

  • html css js
  • angular react vue
  • flutter python