get_post_custom函数概述
与get_post_meta()类似,get_post_custom()也是一个用于获取文章自定义字段值的函数。其优势在于使用更加便捷,特别是在WordPress循环结构中使用时,甚至无需提供任何参数即可直接调用。
从底层实现逻辑来看,get_post_custom()的基础代码结构与get_post_meta()几乎一致,两者大同小异。
get_post_custom()的使用
get_post_custom($postid);
该函数仅接受一个可选参数:$postid,即文章的ID。
实例演示
if (have_posts()) :
while (have_posts()) : the_post();
var_dump(get_post_custom());
endwhile;
endif;
执行后输出的结果如下(假设已设置相关字段):
array(4) {
[“_edit_last”]=>
array(1) {
[0]=>
string(1) “1”
}
[“_edit_lock”]=>
array(1) {
[0]=>
string(12) “1342451729:1”
}
[“_thumbnail_id”]=>
array(1) {
[0]=>
string(3) “228”
}
[“xzmeta”]=>
array(2) {
[0]=>
string(3) “xz1”
[1]=>
string(3) “xz2”
}
}
get_post_custom_values和get_post_custom_keys
由于自定义字段由键(keys)和值(values)组成,有时需要单独获取其中一部分。因此WordPress派生了get_post_custom_values和get_post_custom_keys两个函数。虽然除批量删除字段外,其实际应用场景有限,但在大型CMS主题开发中可能具有重要价值。
此前已介绍过get_post_custom和get_post_meta函数,鉴于自定义字段相关函数数量不多,此处一并整理,但不包含基础实现代码。get_post_custom_values用于获取当前文章指定自定义字段的值,并以数组形式返回。
while (have_posts()) : the_post();
var_dump(get_post_custom_values(‘xzmeta'));
endwhile;
endif;
大致会返回如下结果
(如果自定义字段有设置)
array(2) {
[0]=>
string(3) “xz1”
[1]=>
string(3) “xz2”
}
get_post_custom_keys用于获取当前文章所有的自定义字段的键值。
if (have_posts()) :
while (have_posts()) : the_post();
var_dump(get_post_custom_keys());
endwhile;
endif;
大致会获得以下结果: (如果自定义字段有设置)
array(4) {
[0]=>
string(10) “_edit_last”
[1]=>
string(10) “_edit_lock”
[2]=>
string(13) “_thumbnail_id”
[3]=>
string(6) “xzmeta”
}