函数文档

get_post_custom_keys()

💡 云策文档标注

概述

get_post_custom_keys() 函数用于检索指定文章的自定义字段(meta field)名称。如果文章没有自定义字段,则返回 null。

关键要点

  • 函数返回一个数组,包含文章的所有自定义字段键名(keys),若无字段则返回 null。
  • 参数 $post_id 可选,默认为全局 $post 的 ID,用于指定文章。
  • 内部调用 get_post_custom() 获取自定义字段数据,并提取键名。
  • 函数自 WordPress 1.2.0 版本引入,相关函数包括 get_post_custom() 和 the_meta()。

代码示例

$custom_field_keys = get_post_custom_keys();
if ($custom_field_keys) {
    foreach ($custom_field_keys as $key => $value) {
        $valuet = trim($value);
        if ('_' == $valuet[0])
            continue;
        echo $key . " => " . $value . "<br />";
    }
}

注意事项

  • 函数返回的键名数组是唯一的,即使一个键对应多个值,也只会出现一次。
  • 示例代码中通过检查值首字符是否为下划线来过滤 WordPress 内部维护的键(如 _edit_last 和 _edit_lock)。

📄 原文内容

Retrieves meta field names for a post.

Description

If there are no meta fields, then nothing (null) will be returned.

Parameters

$post_idintoptional
Post ID. Default is the ID of the global $post.

Return

array|void Array of the keys, if retrieved.

Source

function get_post_custom_keys( $post_id = 0 ) {
	$custom = get_post_custom( $post_id );

	if ( ! is_array( $custom ) ) {
		return;
	}

	$keys = array_keys( $custom );
	if ( $keys ) {
		return $keys;
	}
}

Changelog

Version Description
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Default Usage
    The following example will set a variable ($custom_field_keys) as an array containing the keys of all custom fields in the current post, and then print it. Note: the if test excludes values for WordPress internally maintained custom keys such as _edit_last and _edit_lock.

     $value ) {
        $valuet = trim($value);
        if ( '_' == $valuet{0} )
            continue;
        echo $key . " => " . $value . "<br />";
    }
    ?>

    If the post contains custom fields with the keys mykey and yourkey, the output would be something like:

    0 => mykey
    1 => yourkey

    Note: Regardless of how many values (custom fields) are assigned to one key, that key will only appear once in this array.