wp_get_post_parent_id()
云策文档标注
概述
wp_get_post_parent_id() 函数用于获取文章的父级文章ID。它接受一个可选参数来指定文章,并返回父级ID或false。
关键要点
- 参数 $post 可选,可以是文章ID、WP_Post对象或null,默认为全局 $post。
- 返回值:父级文章ID(若无父级则为0),如果文章不存在则返回false。
- 函数内部使用 get_post() 获取文章对象,并检查是否为 WP_Error。
- 仅获取直接父级;如需获取祖先文章,请使用 get_post_ancestors()。
- 自 WordPress 5.9.0 起,$post 参数变为可选;函数在 3.1.0 版本引入。
代码示例
function wp_get_post_parent_id( $post = null ) {
$post = get_post( $post );
if ( ! $post || is_wp_error( $post ) ) {
return false;
}
return (int) $post->post_parent;
}注意事项
- 确保传递有效的文章参数以避免返回false。
- 注意返回值类型:整数或false,需在代码中适当处理。
原文内容
Returns the ID of the post’s parent.
Parameters
$postint|WP_Post|nulloptional-
Post ID or post object. Defaults to global $post.
Default:
null
Source
function wp_get_post_parent_id( $post = null ) {
$post = get_post( $post );
if ( ! $post || is_wp_error( $post ) ) {
return false;
}
return (int) $post->post_parent;
}
Skip to note 2 content
Will Skora
This only obtains the parent immediately of the post.
If you need the parent of a parent page, use
get_post_ancestors