当我想在不使用循环的情况下显示单个帖子的时候,我使用它:
<?php
$post_id = 54;
$queried_post = get_post($post_id);
echo $queried_post->post_title; ?>
问题在于,当我移动网站时,ID通常会发生变化。 有没有办法通过slug查询这篇文章?
答案 0 :(得分:93)
来自WordPress Codex:
<?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;
?>
答案 1 :(得分:62)
怎么样?
<?php
$queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>
答案 2 :(得分:5)
一种较便宜且可重复使用的方法
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 );
}
答案 3 :(得分:2)
由于wordpress api已更改,因此无法使用带有参数'post_name'的get_posts。我修改了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 );
}