【问题标题】:WordPress query single post by slugWordPress 通过 slug 查询单个帖子
【发布时间】:2013-02-05 10:52:57
【问题描述】:

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

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

问题是当我移动网站时,id 通常会发生变化。 有没有办法通过slug查询这个帖子?

【问题讨论】:

  • 为什么在移动站点时ID会改变?除非您使用 WP 的导入/导出功能来移动站点(这不是非常可靠,我建议您避免使用)。如果您只是迁移数据库,则不会发生任何变化。

标签: php wordpress


【解决方案1】:

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

【讨论】:

  • 这显示了 ID - $my_posts[0]->ID; - 但是如何显示页面内容?我已经尝试了一切,但没有任何效果!
  • @JamesWilson 开始使用 kint。 echo $my_posts[0]-&gt;post_content
  • 如果某些 slug 非常相似(例如“工作”与“工作”),这似乎会返回多个结果,因此结果模棱两可
  • 不知道为什么,但我必须将 'name' 更改为 'post_name' 才能让这个查询为我工作
  • 这可以获取特色图片 $feat_image = wp_get_attachment_url( get_post_thumbnail_id($my_posts[0]->ID) );
【解决方案2】:

怎么样?

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

【讨论】:

  • 注意子页面或分层自定义帖子类型:my-slug应该变成my-parent-slug/my-slugcodex.wordpress.org/Function_Reference/…
  • 我阅读这篇文章后的经验支持@Erenor Paz——它可能确实很简单,但是当你依赖 slug 的一致性时它会变得复杂——这可以通过更改父帖子来改变... sigh -- 也许我们可以说服 WordPress 开发人员在路径中允许使用通配符,例如:get_page_by_path('*/my_slug');
  • 不太可靠
【解决方案3】:

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

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

【讨论】:

  • 不错的方法,但我认为'post_name' =&gt; $post_name,应该是'name' =&gt; $post_name,
【解决方案4】:

由于 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' =&gt; true 添加到 get_posts 参数中。
  • 没有必要实例化一个新的WP_Query,这不是“最佳实践”...只需将您的数组提供给get_posts...$posts = get_posts( *your array* ); --(这是一个旧的线程,但也许我的评论会对某人有用)
【解决方案5】:
<?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;
      }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2014-07-23
    • 2016-12-15
    • 2015-02-01
    • 1970-01-01
    • 2014-02-08
    • 2019-12-29
    相关资源
    最近更新 更多