問題描述
是否可以抓住自定義帖子型別的帖子 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。