Wordpress 3.0
如何在WordPress中获得标题文章?
我想使用帖子的title
将特定帖子的内容放入页面。据我所知,我不能直接用get_post()
来做。
我可以假设蛮力的方式可能是什么,但我怀疑有更优雅的方式?
Wordpress 3.0
如何在WordPress中获得标题文章?
我想使用帖子的title
将特定帖子的内容放入页面。据我所知,我不能直接用get_post()
来做。
我可以假设蛮力的方式可能是什么,但我怀疑有更优雅的方式?
<!--1.Get post ID by post title if you know the title or the title variable-->
<?php
$posttitle = 'post_title';
$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;
?>
非常不好的做法,在这样的SQL使用一个转义变量。如果这些数据来自用户,那么它很危险,因为它允许SQL注入攻击。而是使用$ wpdb-> prepare,如下所示:$ postid = $ wpdb-> get_var($ wpdb-> prepare(“SELECT ID FROM {$ wpdb-> posts} WHERE post_title =%s”,$ posttitle)); – 2013-07-29 18:41:41
有关非常类似的问题,请参阅my answer。执行而不是用非转义字符串查询数据库。
当你可以使用wordpress自己的函数来做这件事时,不需要SQL查询。
$page = get_page_by_title('Startsida');
$page_id = $page->ID;
您可以使用此:
1)
global $wpdb;
$your_title = "yourtitle";
$id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = $your_title");
echo $id;
或2)
$slug_to_get = 'my_title_or_slug';
// you can use custom post type too
$posttypee='post';
$args=array(
'title' => $slug_to_get,
'post_type' => $posttypee,
'post_status' => 'publish'
);
$my_posts = get_posts($args);
if($my_posts) {
echo 'ID on the first post found '.$my_posts[0]->ID;
}
由于安全原因,应尽可能使用wp函数。 @查看答案:http://stackoverflow.com/a/12518634/288644 – 2015-01-10 21:50:33
post_exists是一个很好的功能:
https://developer.wordpress.org/reference/functions/post_exists/
<?php
$post_id = post_exists('Your title');
// return id or 0 if post doesn't exists.
if($post_id>0)
get_post($post_id);
如果没有你在这里的answere的符合这个要求,你可能会发现http://wordpress.stackexchange.com/值得一去=) – Rob 2010-08-28 15:44:20