2010-07-31 36 views
1

近日,在WordPress的Trac的補充,可以使用通過取標題的帖子:相反wordpress中的get_page_by_title。如何使用獲取帖子?

get_page_by_title

查詢數據庫直線上升的。如果我想獲得一篇題爲「我的農場」的帖子,我將如何更改參數以便搜索帖子(或帖子類型?):

$ page_title ='Joey in the forest';

'character'是帖子類型。但不知道如何工作。我假設默認返回是id,這將是$ post-> ID。不確定如果我使用帖子類型,會是什麼。

感謝任何人對這個

回答

2

我寫a function(在錯誤報告的鏈接)幫助它正是這麼做的:

/** 
* Retrieves a post/page/custom-type/taxonomy ID by its title. 
* 
* Returns only the first result. If you search for a post title 
* that you have used more than once, restrict the type. 
* Or don’t use this function. :) 
* Simple usage: 
* $page_start_id = id_by_title('Start'); 
* 
* To get the ID of a taxonomy (category, tag, custom) set $tax 
* to the name of this taxonomy. 
* Example: 
* $cat_css_id = id_by_title('CSS', 0, 'category'); 
* 
* The result is cached internally to save db queries. 
* 
* @param string  $title 
* @param string  $type Restrict the post type. 
* @param string|bool $tax Taxonomy to search for. 
* @return int   ID or -1 on failure 
*/ 
function id_by_title($title, $type = 'any', $tax = FALSE) 
{ 
    static $cache = array(); 

    $title = mysql_real_escape_string(trim($title, '"\'')); 

    // Unique index for the cache. 
    $index = "$title-$type-" . ($tax ? $tax : 0); 

    if (isset ($cache[$index])) 
    { 
     return $cache[$index]; 
    } 

    if ($tax) 
    { 
     $taxonomy  = get_term_by('name', $title, $tax); 
     $cache[$index] = $taxonomy ? $taxonomy->term_id : -1; 

     return $cache[$index]; 
    } 

    $type_sql = 'any' == $type 
     ? '' 
     : "AND post_type = '" 
      . mysql_real_escape_string($type) . "'"; 

    global $wpdb; 

    $query = "SELECT ID FROM $wpdb->posts 
     WHERE (
       post_status = 'publish' 
      AND post_title = '$title' 
      $type_sql 
     ) 
     LIMIT 1"; 

    $result = $wpdb->get_results($query); 
    $cache[$index] = empty ($result) ? -1 : (int) $result[0]->ID; 

    return $cache[$index]; 
} 
+0

其實,剛發現他們補充說, 「文章類型」 參數get_page_by_title。在代碼中顯示它。但是這個代碼非常好。非常感謝! – James 2010-08-02 02:05:27

+1

不知道爲什麼這還沒有得到任何upvotes,這是我遇到的這個問題的唯一可靠的答案,謝謝! – nimrod 2013-04-28 13:57:33

1

自從我偶然發現這個頁面,別人還不如。

get_page_by_title()也處理帖子和自定義帖子類型。

請注意,即使該帖子被刪除,它也會獲得數據庫中的第一個帖子/頁面項。

樣品:

$post = get_page_by_title('sample-post','post'); 
echo $post->ID 
相關問題