函数文档

get_post_custom_values()

💡 云策文档标注

概述

get_post_custom_values() 函数用于检索自定义文章字段的值,基于指定的键和文章ID。它返回一个数组或null,适用于WordPress开发中处理文章元数据。

关键要点

  • 函数检索自定义文章字段的值,参数包括键(可选,默认为空)和文章ID(可选,默认为全局$post的ID)。
  • 返回值为数组或null,如果键为空则返回null,否则返回对应键的值。
  • 函数内部调用get_post_custom()来获取所有文章元字段,然后提取指定键的值。
  • 相关函数包括get_post_custom()和the_meta(),用于获取和显示文章自定义字段。
  • 函数自WordPress 1.2.0版本引入,属于核心功能。

代码示例

$mykey_values = get_post_custom_values( 'my_key' );

foreach ( $mykey_values as $key => $value ) {
    echo "$key => $value ( 'my_key' )";
}

注意事项

  • 参数不应被视为可选,必须提供键值以正确检索数据。
  • 如果键不存在或为空,函数返回null,需在代码中处理此情况。
  • 函数仅返回指定键的值,不返回其他元字段信息。

📄 原文内容

Retrieves values for a custom post field.

Description

The parameters must not be considered optional. All of the post meta fields will be retrieved and only the meta field key values returned.

Parameters

$keystringoptional
Meta field key. Default empty.
$post_idintoptional
Post ID. Default is the ID of the global $post.

Return

array|null Meta field values.

Source

function get_post_custom_values( $key = '', $post_id = 0 ) {
	if ( ! $key ) {
		return null;
	}

	$custom = get_post_custom( $post_id );

	return isset( $custom[ $key ] ) ? $custom[ $key ] : null;
}

Changelog

Version Description
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Default usage example.

    Let’s assume the current post has 3 values associated with the (custom) field my_key.

    You could show them through:

    $mykey_values = get_post_custom_values( 'my_key' );
    
    foreach ( $mykey_values as $key => $value ) {
    	echo "$key => $value ( 'my_key' )<br />"; 
    }

    The above example will output:

    0 => First value ( 'my_key' )
    1 => Second value ( 'my_key' )
    2 => Third value ( 'my_key' )