0

When creating a CMB2 file_list for images upload to populate a gallery CMB2 online example is laking to show options such as the img alt tag and adding a classes to the images. I do not know how to access the images but only via the supplied code below. I need to add a class to the first image in the gallery for example and adding the alt tag? If anyone can help I would be thankful!

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

// Get the list of files
$files = get_post_meta( get_the_ID(), $file_list_meta_key, 1 );

// Loop through them and output an image
foreach ( (array) $files as $attachment_id => $attachment_url ) {

  echo '<div class="slide">';                   
  echo wp_get_attachment_image( $attachment_id, $img_size);
  echo '</div>';                    
  }             
}                   
cmb2_output_file_list( 'bs_bautage_pic', '');
Refael
  • 145
  • 2
  • 12

1 Answers1

0

You can pass conditional arguments for fourth parameter in wp_get_attachment_image(). This fourth parameter is for the custom attributes. In the function, custom attributes are added for the first image only. Please check following example.

function cmb2_output_file_list( $file_list_meta_key, $img_size = '' ) {
    $files = get_post_meta( get_the_ID(), $file_list_meta_key, 1 );

    $counter = 0;
    foreach ( (array) $files as $attachment_id => $attachment_url ) {
        echo '<div class="slide">';
        $args = array();
        if ( 0 === $counter ) {
            $args = array(
                'alt'   => 'Sample Text',
                'class' => 'custom-class',
                );
        }
        echo wp_get_attachment_image( $attachment_id, $img_size, false, $args );
        echo '</div>';
        $counter++;
    }
}
Nilambar Sharma
  • 1,732
  • 6
  • 18
  • 23