目前,当我想在不使用循环的情况下显示单个帖子时,我使用这个:
<?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;
?>
怎么样?
<?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 );
}
由于 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 );
}
<?php
$page = get_page_by_path('slug', ARRAY_N);
echo $page->post_content
function get_id_by_slug($page_slug) {
$page = get_page_by_path($page_slug, ARRAY_N);
if ($page[0] > 0) {
return $page[0];
}else{
return null;
}
}