当我们在 CFS 插件中创建一组字段时,我们在技术上创建了一个名为 cfs 的自定义帖子类型
我们还将创建三个自定义字段:
- cfs_extras - 这是存储字段组设置的位置
- cfs_rules - 显示字段组的条件,应在哪个自定义帖子类型或分类中显示
- cfs_fields - 组的其他字段存储在这里
如果我们需要为一组字段查找字段,首先我们必须进行这样的查询
$my_fields_group_name = 'test';
$query = get_posts( 'no_found_rows=true&fields=ids&post_type=cfs&s=' . $my_fields_group_name );
$my_fields_group_post_id = $query[0];
然后从自定义字段“cfs_fields”中获取字段的名称
$my_fields = get_post_meta($my_fields_group_post_id , "cfs_fields", true);
print_r($my_fields);
现在我们有了所有自定义字段键,我们可以获取这些字段的值
$current_post_id = get_the_id();
foreach($my_fields as $my_field) {
$custom_field_key = $my_field ['name'];
$custom_field_value = get_post_meta($current_post_id , $custom_field_key, true);
echo $custom_field_key . ' - ' . $custom_field_value;
echo '<br>';
}
这是所有的代码组合
$my_fields_group_name = 'test';
$query = get_posts( 'no_found_rows=true&fields=ids&post_type=cfs&s=' . $my_fields_group_name );
$my_fields_group_post_id = $query[0];
$my_fields = get_post_meta($my_fields_group_post_id , "cfs_fields", true);
print_r($my_fields);
echo '<br>';
$current_post_id = get_the_id();
foreach($my_fields as $my_field) {
$custom_field_key = $my_field ['name'];
$custom_field_value = get_post_meta($current_post_id , $custom_field_key, true);
echo $custom_field_key . ' - ' . $custom_field_value;
echo '<br>';
}
更新
如果不想每次都查询,可以获取自定义post fields group的post_id
$my_fields_group_name = 'test';
$query = get_posts( 'no_found_rows=true&fields=ids&post_type=cfs&s=' . $my_fields_group_name );
$my_fields_group_post_id = $query[0];
并在代码中直接使用这个id
$my_id = 28;
$my_fields = get_post_meta($my_id , "cfs_fields", true);
$current_post_id = get_the_id();
foreach($my_fields as $my_field) {
$custom_field_key = $my_field ['name'];
$custom_field_value = get_post_meta($current_post_id , $custom_field_key, true);
echo $custom_field_key . ' - ' . $custom_field_value;
echo '<br>';
}