問題描述

當我想要顯示一個單獨的帖子而不使用迴圈的那一刻,我用這個:

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

問題是當我移動網站時,id 通常會發生變化。有沒有辦法透過 slug 查詢這個帖子?

最佳解決辦法

從 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

次佳解決辦法

怎麼樣?

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

第三種解決辦法

一種便宜又可重複使用的方法

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 );
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。