【问题标题】:get post by post name instead of id通过帖子名称而不是 id 获取帖子
【发布时间】:2012-10-16 00:09:14
【问题描述】:

好的,我现在有这个代码。

<?php

$post_id = 266;
echo "<div id='widgets-wrapper3'><div id='marginwidgets' style='overflow: auto; max-    width: 100%; margin: 0 auto; border: none !important;'>";
$queried_post = get_post($post_id); 
echo "<div class='thewidgets'>";
echo substr($queried_post->post_content, 0, 500);
echo "<a href='".get_permalink( 26 )."' title='Read the whole post' class='rm'>Read     More</a>";
echo "</div>";

echo "</div></div>";

?>

正如您在上面的代码中看到的那样,例程是通过 ID 获取帖子,但是出于 SEO 目的,我的永久链接更改为帖子名称而不是帖子 ID。如何通过帖子名称获取帖子?

希望这里有人能弄清楚。谢谢。

【问题讨论】:

标签: php wordpress


【解决方案1】:

get_page_by_path()

WordPress 有一个内置功能可能会有所帮助,但请注意几句。

&lt;?php get_page_by_path( $page_path, $output, $post_type ) ?&gt;

Here's the relevant Codex entry.

要获取帖子而不是页面,您只需提供“帖子”作为$post_type 参数,通常将OBJECT(不带引号)作为$output 类型,如下所示:

&lt;?php get_page_by_path( 'my_post_slug', OBJECT, 'post' ) ?&gt;

注意此功能不会检查匹配帖子的发布或私人状态。如果您要查找的项目是附件,这很好,但对于帖子和页面(即草稿、私人帖子等)可能会有问题。

注意如果它您正在寻找的页面,并且该页面是分层的(即:它有一个父级),那么您需要提供整个路径,即:'parent_page_slug/my_page_slug'。

WP_Query / get_posts()

如果其中任何一个对您来说有问题,那么您应该考虑只使用WP_Query 类来获取name 的帖子:

$found_post = null;

if ( $posts = get_posts( array( 
    'name' => 'my_post_slug', 
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1
) ) ) $found_post = $posts[0];

// Now, we can do something with $found_post
if ( ! is_null( $found_post ) ){
    // do something with the post...
}

【讨论】:

  • @Torben 您的评论不正确。 name 是要使用的正确参数。
【解决方案2】:

使用WP_Query。此函数将检索具有给定名称的第一个帖子,如果没有找到,则返回 null

function get_post_by_name(string $name, string $post_type = "post") {
    $query = new WP_Query([
        "post_type" => $post_type,
        "name" => $name
    ]);

    return $query->have_posts() ? reset($query->posts) : null;
}

默认情况下,这将搜索 post 类型的项目:

get_post_by_name("my-post")

作为第二个参数,您可以将其设置为其他参数:

get_post_by_name("my-page", "page")

【讨论】:

    【解决方案3】:
    function get_post_by_name($post_name, $output = OBJECT) {
        global $wpdb;
            $post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type='post'", $post_name ));
            if ( $post )
                return get_post($post, $output);
    
        return null;
    }
    

    这个。

    【讨论】:

      猜你喜欢
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-14
      相关资源
      最近更新 更多