更新时间:2023-11-26 10:10:22
使用 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")