Support Forum
Support › Meta Box Group › Image display in a Group ProblemResolved
I’ve been trying to figure out how to use the Field ‘Group’ using Metabox AIO and displaying the content on the front end with a code block.
I can’t seem to find any documentation lately for use of the Metabox AIO as most of what I find seems to be for using functions to build the custom fields.
I’ve taken one of your examples and I’ve built a group with an ID of ‘cars’ that is cloneable. I’ve added 3 fields with IDs of ‘brand’, ‘date’ and ‘color’.
I’ve attached it to a page and added 3 different cars.
In a code block I’ve placed this code:
<?php
$cars = rwmb_meta( 'car' ); // ID of the group
foreach ( $cars as $car ) {
if ( ! empty( $car ) ) {
echo '<h4>Car info</h4>';
echo '<p>Brand: ', $car['brand'], '</p>'; // Access sub-field via its ID.
echo '<p>Date: ', $car['date'], '</p>';
echo '<p>Color: <span style="color:', $car['color'], '"><strong>Colour</strong></span></p>';
}
}
?>
It’s display the 3 different cars that I inputed values for perfectly.
Where I’m having a problem is when I add a 4th custom field of Single Image with ID of ‘my_image’ and add an image to each of the cars. I’ve tried pretty much everything I could think of code wise to display the image on the frontend but haven’t been successful.
Was hoping you might be able to straighten me out. Any help with this would be greatly appreciated.
Hi,
To output the subfield image in a group, please try to use this example code
$group = rwmb_meta( 'group_id' );
$image_ids = $group['image_key'] ?? : [];
foreach ( $image_ids as $image_id ) {
$image = RWMB_Image_Field::file_info( $image_id, ['size' => 'thumbnail'] );
echo '<img src="' . $image['url'] . '">';
}
It is already added to the documentation https://docs.metabox.io/extensions/meta-box-group/#sub-field-values
I appreciate the answer though if I replace the code you and your documentation have provided I get an error for line 3
<?php
$group = rwmb_meta( 'car' );
$image_ids = $group['image_key'] ?? : [];
foreach ( $image_ids as $image_id ) {
$image = RWMB_Image_Field::file_info( $image_id, ['size' => 'thumbnail'] );
echo '<img src="' . $image['url'] . '">';
}
?>
Even though it says image_key and not image_id I tried it as above, then replaced the 'image_key' with the id for my image, same result for both attempts, error line 3
Hi Dan,
If you use the field single_image
, then you can remove the for
loop and access the image ID directly from the group value. Like this
<?php
$group = rwmb_meta( 'car' );
$image_id = $group['my_image'];
$image = RWMB_Image_Field::file_info( $image_id, ['size' => 'thumbnail'] );
echo '<img src="' . $image['url'] . '">';
?>
That worked, thanks!