$meta = get_post_meta($post_id,'',true);
Run Code Online (Sandbox Code Playgroud)
带回$ post_id的所有元值,但它返回每个值的数组,如下所示:

如果我将第三个参数 - single - 设置为false但它设置为true,我可能会期待这个.我没有在codex中找到任何关于key为空时返回的确切内容的内容.
有人必须在这里获取信息,并知道如何获取所有键,每个键值是单个值而不是值数组?
答案是:这是设计的,但似乎没有在食典委中记录.
如果你看一下真正的文档(源代码),你会看到那些get_post_meta调用get_metadata.通过检查代码get_metadata,我们可以看到,如果$meta_key没有发布,那么它在评估之前返回值是否$single设置:
// Previously, $meta_cache is set to the contents of the post meta data
// Here you see if there is no key set, it just returns it all
if ( ! $meta_key ) {
return $meta_cache;
}
// It's not until later than $single becomes a factor
if ( isset($meta_cache[$meta_key]) ) {
if ( $single )
return maybe_unserialize( $meta_cache[$meta_key][0] );
else
return array_map('maybe_unserialize', $meta_cache[$meta_key]);
}
Run Code Online (Sandbox Code Playgroud)
如果您使用的是PHP 5.3+,您可以通过以下方式获得所需内容:
// Get the meta values
$meta = get_post_meta($post_id,'',true);
// Now convert them to singles
$meta = array_map(function($n) {return $n[0];}, $meta);
Run Code Online (Sandbox Code Playgroud)
或者,如果你想变得非常花哨,你可以在get_post_meta函数周围编写自己的"包装器",如下所示:
function get_all_post_meta($post_id) {
// Get the meta values
$meta = get_post_meta($post_id,'');
// Now convert them to singles and return them
return array_map(function($n) {return $n[0];}, $meta);
}
Run Code Online (Sandbox Code Playgroud)
你可以这样使用:
$meta = get_all_post_meta($post_id);
Run Code Online (Sandbox Code Playgroud)
或者,如果你不是PHP 5.3+(你应该是!),你可以这样做:
function get_all_post_meta($post_id) {
// Get the meta values
$meta = get_post_meta($post_id,'');
foreach($meta AS $key => $value) {
$meta[$key] = $value[0];
}
return $meta;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1015 次 |
| 最近记录: |