問題描述

是否可以抓住自定義帖子類型的帖子 id 只是從 s lug?

我知道我們可以通過使用標題從 id 獲得。但是在一個自定義的帖子類型中可以有相同的標題,因為 lug s 是獨一無二的可能嗎?

最佳解決方案

你可以使用 get_page_by_path() – 不要讓名字愚弄你,第三個參數是帖子類型:

if ( $post = get_page_by_path( 'the_slug', OBJECT, 'post_type' ) )
    $id = $post->ID;
else
    $id = 0;

次佳解決方案

如果您等待幾天,並升級到 12 月 8 日發佈的 WordPress 4.4(AFAIK),您可以在 WP_Query 中使用新的 post_name__in 參數,該參數需要一系列的 s s

例子

如果您需要完整的 post 對象

$args = [
    'post_type'      => 'my_custom_post_type',
    'posts_per_page' => 1,
    'post_name__in'  => ['post-slug']
];
$q = get_posts( $args );
var_dump( $q );

如果你只需要 ID

$args = [
    'post_type'      => 'my_custom_post_type',
    'posts_per_page' => 1,
    'post_name__in'  => ['post-slug'],
    'fields'         => 'ids'
];
$q = get_posts( $args );
var_dump( $q );

參考文獻

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