当我想不使用循环显示单个帖子时,请使用以下命令:
<?php
$post_id = 54;
$queried_post = get_post($post_id);
echo $queried_post->post_title; ?>
问题是,当我移动网站时,id通常会更改。有没有办法通过slug查询此帖子?
Answers:
从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;
?>
echo $my_posts[0]->post_content
怎么样?
<?php
$queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>
由于wordpress api已更改,因此无法将get_posts与参数“ 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 );
}
'no_found_rows' => true
获得更高的性能,我还将添加到get_posts参数中。