Support Forum
Support › Meta Box Group › How to Display a Group of FieldsResolved
I have a group defined with two fields in it: a text field and a URL field. The idea is the text field is the Link Text and the URL is ... the URL. How can I display these as links on my template?
Partially answered my own question by reading the MB Group documentation. Created a custom shortcode like this. However, this is not returning the appropriate values.
Do you see any issues?
add_shortcode( 'references', function() {
$group = rwmb_meta( 'references' );
if ( empty( $group ) ) {
return '';
}
$output = '';
// Reference URL
$rlabel = $group['reference_label'] ?? '';
$rurl = $group['reference_url'] ?? '';
$output .= '<a href="' . $rurl . '">' . $rlabel . '</a>';
return $output;
} );
Hi David,
Can you please share the code that creates the group and subfields? If you are using the builder, please refer to this documentation https://docs.metabox.io/extensions/meta-box-builder/#getting-php-code
<?php
add_filter( 'rwmb_meta_boxes', 'your_prefix_function_name' );
function your_prefix_function_name( $meta_boxes ) {
$prefix = '';
$meta_boxes[] = [
'title' => __( 'References', 'your-text-domain' ),
'id' => 'references',
'post_types' => ['control'],
'fields' => [
[
'id' => $prefix . 'references',
'type' => 'group',
'clone' => true,
'fields' => [
[
'name' => __( 'Reference Label', 'your-text-domain' ),
'id' => $prefix . 'myreference_label',
'type' => 'text',
],
[
'name' => __( 'Reference URL', 'your-text-domain' ),
'id' => $prefix . 'myreference_url',
'type' => 'url',
],
],
],
],
];
return $meta_boxes;
}
Here's my latest shortcode function:
add_shortcode( 'references', function() {
$group = rwmb_meta( 'references' );
//return $group;
if ( empty( $group ) ) {
return '';
}
$output = '';
// Reference URL
$rlabel = $group['myreference_label'] ?? '';
$rurl = $group['myreference_url'] ?? '';
$output .= '<a href="' . $rurl . '">' . $rlabel . '</a>';
return $output;
});
Hi,
It's a cloneable group, then you need to create a loop to iterate through an array of groups.
add_shortcode( 'references', function() {
$groups = rwmb_meta( 'references' );
//return $groups;
if ( empty( $groups ) ) {
return '';
}
$output = '';
foreach ( $groups as $group ) {
// Reference URL
$rlabel = $group['myreference_label'] ?? '';
$rurl = $group['myreference_url'] ?? '';
$output .= '<a href="' . $rurl . '">' . $rlabel . '</a>';
}
return $output;
} );
Read more on the documentation https://docs.metabox.io/extensions/meta-box-group/#getting-sub-field-values
That fixed it. Thank you.