通过帖子名称而不是 id 获取帖子 [英] get post by post name instead of id

查看:31
本文介绍了通过帖子名称而不是 id 获取帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我目前有这个代码.

Ok i have this code currently.

<?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.如何通过帖子名称获取帖子?

As you can see to the above code, the routine is to get the post by ID, but my permalinks change into post name instead of post id for SEO purposes. How do I get the post by post name?

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

Hope someone here could figure it out. Thank you.

推荐答案

使用 WP_Query.此函数将检索具有给定名称的第一篇文章,如果未找到任何内容,则为 null:

Use WP_Query. This function will retrieve the first post with the given name, or null if nothing is found:

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 类型的项目:

By default this will search for an item of the type post:

get_post_by_name("my-post")

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

As a second argument you can set that to something else:

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

这篇关于通过帖子名称而不是 id 获取帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆