Wordpress通过slug查询单个帖子

Geo*_*iko 71 php wordpress

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

<?php
$post_id = 54;
$queried_post = get_post($post_id);
echo $queried_post->post_title; ?>
Run Code Online (Sandbox Code Playgroud)

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

zti*_*rom 98

来自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;
?>
Run Code Online (Sandbox Code Playgroud)

WordPress Codex获取帖子

  • 不知道为什么,但我必须将“名称”更改为“post_name”才能使此查询对我有用 (2认同)

Mik*_*cia 65

怎么样?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>
Run Code Online (Sandbox Code Playgroud)

  • 注意子页面或分层自定义帖子类型:`my-slug`应该变成`my-parent-slug/my-slug`:https://codex.wordpress.org/Function_Reference/get_page_by_path#Examples (7认同)
  • 我阅读这篇文章后的经验支持@Erenor Paz - 它可能确实非常简单但是当你依赖slug的一致性时它会变得复杂 - 只需更改父帖子即可改变...*叹气* - 也许我们可以说服WordPress开发者在路径中允许使用通配符,例如:get_page_by_path('*/my_slug'); (2认同)

小智 6

由于 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 );
}
Run Code Online (Sandbox Code Playgroud)


小智 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 );
}
Run Code Online (Sandbox Code Playgroud)