当WordPress具有本机函数来执行特定作业时,几乎永远不会建议运行自定义SQL。鼻涕虫或post_name
在页面的路径(URL)中也使用了,用于在访问此类页面时标识并返回该页面的内容。这意味着,我们可以使用get_page_by_path()
只需将slug(post\\u name)传递给函数并获取返回的页面对象。
get_page_by_path (
string $page_path,
string $output = OBJECT,
string|array $post_type = \'page\'
)
像许多其他函数和命名约定一样
post_name
实际上是slug,而不是WordPress中的名称,
get_page_by_path()
\'s的名称令人困惑,而且很愚蠢,因为您可以将任何post类型传递给函数
我们可以使用get_page_by_path()
如果找不到页面或页面对象成功,则将不返回任何内容。让我们编写一个适当的包装函数,该函数在失败时将返回false,并且无论页面是否存在,都将始终返回页面对象
function get_post_by_post_name( $slug = \'\', $post_type = \'\' )
{
//Make sure that we have values set for $slug and $post_type
if ( !$slug
|| !$post_type
)
return false;
// We will not sanitize the input as get_page_by_path() will handle that
$post_object = get_page_by_path( $slug, OBJECT, $post_type );
if ( !$post_object )
return false;
return $post_object;
}
然后可以按如下方式使用它
if ( function_exists( \'get_post_by_post_name\' ) ) {
$post_object = get_post_by_post_name( \'post-name-better-known-as-slug\', \'your_desired_post_type\' );
// Output only if we have a valid post
if ( $post_object ) {
echo apply_filters( \'the_title\', $post_object->post_title );
}
}
如果您真的只需要返回帖子标题,我们可以稍微修改一下函数
function get_post_title_by_post_name( $slug = \'\', $post_type = \'\' )
{
//Make sure that we have values set for $slug and $post_type
if ( !$slug
|| !$post_type
)
return false;
// We will not sanitize the input as get_page_by_path() will handle that
$post_object = get_page_by_path( $slug, OBJECT, $post_type );
if ( !$post_object )
return false;
return apply_filters( \'the_title\', $post_object->post_title );
}
然后按如下方式使用
if ( function_exists( \'get_post_title_by_post_name\' ) ) {
$post_title = get_post_title_by_post_name( \'post-name-better-known-as-slug\', \'your_desired_post_type\' );
// Output only if we have a valid post
if ( $post_title ) {
echo $post_title;
}
}