93

目前,当我想在不使用循环的情况下显示单个帖子时,我使用这个:

<?php
$post_id = 54;
$queried_post = get_post($post_id);
echo $queried_post->post_title; ?>

问题是当我移动网站时,id 通常会改变。有没有办法通过slug查询这篇文章?

4

5 回答 5

133

来自 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;
?>

WordPress Codex 获取帖子

于 2013-02-20T12:59:40.603 回答
80

怎么样?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>
于 2015-04-21T10:58:23.653 回答
10

一种更便宜且可重复使用的方法

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 );
}
于 2016-04-03T09:39:29.337 回答
6

由于 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 );
}
于 2018-01-30T10:26:38.643 回答
0
<?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;
      }
}
于 2021-12-09T12:58:40.117 回答