我正在使用Custom Metaboxes 2,我无法在前端显示可重复的组值。我有一个可重复的组,只有一个文本字段。
我首先使用后端代码,然后是前端代码。
add_action( 'cmb2_init', 'awc_register_repeatable_group_field_metabox' );
function awc_register_repeatable_group_field_metabox() {
// Start with an underscore to hide fields from custom fields list
$prefix = '_awc_';
/**
* Repeatable Field Groups
*/
$cmb_group = new_cmb2_box( array(
'id' => $prefix . 'songs',
'title' => __( 'Track Listing', 'cmb2' ),
'object_types' => array( 'awc_discography', ),
) );
// $group_field_id is the field id string, so in this case: $prefix . 'demo'
$group_field_id = $cmb_group->add_field( array(
'id' => $prefix . 'demo',
'type' => 'group',
//'description' => __( 'Generates reusable form entries', 'cmb2' ),
'options' => array(
'group_title' => __( 'Track {#}', 'cmb2' ), // {#} gets replaced by row number
'add_button' => __( 'Add Another Track', 'cmb2' ),
'remove_button' => __( 'Remove Track', 'cmb2' ),
'sortable' => true, // beta
),
) );
/**
* Group fields works the same, except ids only need
* to be unique to the group. Prefix is not needed.
*
* The parent field's id needs to be passed as the first argument.
*/
$cmb_group->add_group_field( $group_field_id, array(
'name' => __( 'Title', 'cmb2' ),
'id' => 'title',
'type' => 'text',
) );
}
前端:
$entries = get_post_meta( get_the_ID(), $prefix . 'songs', true );
foreach ( (array) $entries as $key => $entry ) {
$songtitle = '';
if ( isset( $entry['demo'] ) )
$title = esc_html( $entry['demo'] );
// Do something with the data
echo $title; // Don't know if this is the correct method.
}
答案 0 :(得分:6)
您的前端代码中是否定义了$prefix
?那是我唯一能看到的错误。如果未定义$prefix
,则您使用密钥songs
而不是_awc_songs
查找post_meta。