函数文档

get_post_parent()

💡 云策文档标注

概述

get_post_parent() 函数用于检索给定文章的父文章对象。它接受一个可选参数,返回父文章的 WP_Post 对象或 null。

关键要点

  • 参数 $post 可选,可以是文章 ID、WP_Post 对象或 null,默认为全局 $post。
  • 返回值是父文章的 WP_Post 对象,若无父文章则返回 null。
  • 函数内部使用 get_post() 获取文章数据,并检查 post_parent 属性。
  • 该函数自 WordPress 5.7.0 版本引入。

代码示例

function get_post_parent( $post = null ) {
    $wp_post = get_post( $post );
    return ! empty( $wp_post->post_parent ) ? get_post( $wp_post->post_parent ) : null;
}

注意事项

  • 确保传入有效的文章 ID 或 WP_Post 对象,否则可能返回意外结果。
  • 相关函数包括 get_post() 用于获取文章数据,has_post_parent() 用于检查是否有父文章。

📄 原文内容

Retrieves the parent post object for the given post.

Parameters

$postint|WP_Post|nulloptional
Post ID or WP_Post object. Default is global $post.

Default:null

Return

WP_Post|null Parent post object, or null if there isn’t one.

Source

function get_post_parent( $post = null ) {
	$wp_post = get_post( $post );
	return ! empty( $wp_post->post_parent ) ? get_post( $wp_post->post_parent ) : null;
}

Changelog

Version Description
5.7.0 Introduced.