函数文档

post_custom()

💡 云策文档标注

概述

post_custom() 函数用于检索文章的自定义元数据字段。它基于给定的键名返回对应的值,支持数组或字符串格式,并在键不存在时返回 false。

关键要点

  • 参数 $key 为必需,指定要检索的元数据键名。
  • 返回值可以是数组(多个值)、字符串(单个值)或 false(键不存在)。
  • 函数内部调用 get_post_custom() 获取所有元数据,然后根据键的存在性和值数量返回相应结果。

代码示例

function post_custom( $key = '' ) {
	$custom = get_post_custom();

	if ( ! isset( $custom[ $key ] ) ) {
		return false;
	} elseif ( 1 === count( $custom[ $key ] ) ) {
		return $custom[ $key ][0];
	} else {
		return $custom[ $key ];
	}
}

注意事项

  • 该函数自 WordPress 1.5.0 版本引入。
  • 相关函数 get_post_custom() 可用于基于文章 ID 检索所有元数据字段。

📄 原文内容

Retrieves post custom meta data field.

Parameters

$keystringrequired
Meta data key name.

Return

array|string|false Array of values, or single value if only one element exists.
False if the key does not exist.

Source

function post_custom( $key = '' ) {
	$custom = get_post_custom();

	if ( ! isset( $custom[ $key ] ) ) {
		return false;
	} elseif ( 1 === count( $custom[ $key ] ) ) {
		return $custom[ $key ][0];
	} else {
		return $custom[ $key ];
	}
}

Changelog

Version Description
1.5.0 Introduced.