2010-08-28 29 views
12

Wordpress 3.0如何在WordPress中獲得標題文章?

我想使用帖子的title將特定帖子的內容放入頁面。據我所知,我不能直接用get_post()來做。

我可以假設蠻力的方式可能是什麼,但我懷疑有更優雅的方式?

+1

如果沒有你在這裏的answere的符合這個要求,你可能會發現http://wordpress.stackexchange.com/值得一去=) – Rob 2010-08-28 15:44:20

回答

5
<!--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; 
?> 
+10

非常不好的做法,在這樣的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

1

有關非常類似的問題,請參閱my answer。執行而不是用非轉義字符串查詢數據庫。

34
get_page_by_title($id, OBJECT, 'post'); 

你們走了。

+4

http://codex.wordpress.org/Function_Reference/get_page_by_title – Jake 2013-05-29 15:51:24

+0

爲了將來的參考,'get_page_by_title()'的第二個參數需要一個字符串。然而,WP定義了一些頂級變量,如OBJECT('​​OBJECT'),ARRAY_N('ARRAY_N')等等。 – Chris 2016-12-12 16:32:16

4

當你可以使用wordpress自己的函數來做這件事時,不需要SQL查詢。

$page = get_page_by_title('Startsida'); 
$page_id = $page->ID; 
1

您可以使用此:

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; 
    } 
+1

由於安全原因,應儘可能使用wp函數。 @查看答案:http://stackoverflow.com/a/12518634/288644 – 2015-01-10 21:50:33

相關問題