Search code examples
phpwordpresscmb2

CMB2 - Get the first image from file_list


I am using CMB2 file_list for uploading photos e.g. photo gallery. On the home page I need to get only the first photo and not the entire gallery. Below is the function to get all the photo. How can i retrieve only the first photo in the list?

function cmb2_output_file_list( $file_list_meta_key, $img_size = 'medium' ) {

$files = get_post_meta( get_the_ID(), $file_list_meta_key, 1 );
echo '<div class="file-list-wrap">';

foreach ( (array) $files as $attachment_id => $attachment_url ) {
    echo '<div class="file-list-image">';
    echo wp_get_attachment_image( $attachment_id, $img_size );
    echo '</div>';
}
echo '</div>';

}

cmb2_output_file_list( 'wiki_test_file_list', 'small' );

Solution

  • You'd use something like this, make sure to change the meta key to the correct one, this will get the ID and URL of first file in the list:

    $file_list_meta_key = 'wiki_test_file_list';
    $files = get_post_meta( get_the_ID(), $file_list_meta_key, 1 );
    
    $first_id = key($files);
    $first_url = reset($files);