php slug 的 WordPress 查询单个帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14979837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:18:29  来源:igfitidea点击:

WordPress query single post by slug

phpwordpress

提问by George Oiko

For the moment when I want to show a single post without using a loop I use this:

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

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

The problem is that when I move the site, the id's usually change. Is there a way to query this post by slug?

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

回答by ztirom

From the WordPress Codex:

来自 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 Get Posts

WordPress Codex 获取帖子

回答by Mike Garcia

How about?

怎么样?

<?php
   $queried_post = get_page_by_path('my_slug',OBJECT,'post');
?>

回答by Maarten Menten

a less expensive and reusable method

一种成本较低且可重复使用的方法

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 );
}

回答by Nurickan

As wordpress api has changed, you can′t use get_posts with param 'post_name'. I′ve modified Maartens function a bit:

由于 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 );
}