2013-02-20 22 views
47

時,我想展現一個單一的差價,而無需使用一個循環的那一刻我用這個:WordPress的查詢單後由塞

<?php 
$post_id = 54; 
$queried_post = get_post($post_id); 
echo $queried_post->post_title; ?> 

的問題是,當我移動網站,該ID的通常會改變。 有沒有辦法通過slu query查詢這篇文章?

+1

爲什麼移動站點時ID會改變?除非你使用WP的導入/導出功能移動站點(這不是非常可靠,我建議避免)。如果您只是簡單地遷移數據庫,則不會有任何改變。 – Ennui 2013-02-20 13:38:51

回答

75

從WordPress食品:

<?php 
$the_slug = 'my_slug'; 
$args = array(
    'name'  => $the_slug, 
    'post_type' => 'post', 
    'post_status' => 'publish', 
    'numberposts' => 1 
); 
$my_posts = get_posts($args); 
if($my_posts) : 
    echo 'ID on the first post found ' . $my_posts[0]->ID; 
endif; 
?> 

WordPress Codex Get Posts

+1

這顯示了ID - $ my_posts [0] - > ID; - 但我如何顯示頁面內容?我嘗試了一切,沒有任何作品! – 2015-01-20 15:23:22

+1

@JamesWilson開始使用kint。 'echo $ my_posts [0] - > post_content' – Toskan 2015-02-10 09:59:09

+0

如果某些slu are非常相似(例如'work'vs'working'),這似乎會返回多個結果,從而導致模糊結果 – 2016-08-16 14:38:44

42

怎麼樣?

<?php 
    $queried_post = get_page_by_path('my_slug',OBJECT,'post'); 
?> 
+0

這是迄今爲止最好的方式。 – 2016-06-21 09:49:30

+0

這是多少年來我沒有注意到我?我同意,最好的方式抓住一個單一的職位對象。 – aequalsb 2016-08-06 02:48:35

+3

注意兒童網頁或分層定製的帖子類型:'my-slug'應該成爲'my-parent-slug/my-slug':https://codex.wordpress.org/Function_Reference/get_page_by_path#Examples – 2017-03-16 12:22:43

3

更便宜和可重複使用的方法

function get_post_id_by_name($post_name, $post_type = 'post') 
{ 
    $post_ids = get_posts(array 
    (
     'post_name' => $post_name, 
     'post_type' => $post_type, 
     'numberposts' => 1, 
     'fields' => 'ids' 
    )); 

    return array_shift($post_ids); 
} 
0

由於WordPress的API已經改變了,你不容使用get_posts與PARAM 'POST_NAME'。我已經修改了Maartens的一些功能:

function get_post_id_by_slug($slug, $post_type = "post") { 
    $query = new WP_Query(
     array(
      'name' => $slug, 
      'post_type' => $post_type, 
      'numberposts' => 1, 
      'fields'  => 'ids', 
     )); 
    $posts = $query->get_posts(); 
    return array_shift($posts); 
}