Title on the current image wordpress

I want to show the specific title of the images from media library, and I have this code but the code only shows the title of the first image and not the current image being posted please help,here is my code:

<?php
$args = array( 'post_type' => 'attachment', 'posts_per_page' => 1, 'post_status' =>'any', 'post_parent' => $post->ID ); 

  $attachments = get_posts( $args );
     if ( $attachments) {
        foreach ( $attachments as $attachment ) {

     $the_title = apply_filters( 'the_title', $attachment->post_title );

  }
}
    $output = sprintf(
        '<img%4$s src="%1$s" alt="%2$s" class="et-waypoint et_pb_image%3$s%5$s" title="'.$the_title.'"/>',
        esc_attr( $src ),
        esc_attr( $alt ),
                esc_attr( " et_pb_animation_{$animation}" ),
        ( '' !== $module_id ? sprintf( ' id="%1$s"', esc_attr( $module_id ) ) : '' ),
        ( '' !== $module_class ? sprintf( ' %1$s', esc_attr( $module_class ) ) : '' )
    );?>

Related posts

Leave a Reply

1 comment

  1. Currently you’re code is wrong.

    In the ‘foreach’ you’re looping every attachmentbut you’re always overriding $the _title.

    Imagine, you have the attachments A, B and C, your foreachis looping over the array attachment.

    1. The first element would be A, you save the title of A to $the_title

    2. The second element would be B, you save the title of B to $the_title, you’re overriding the value of A’s title

    3. The third element would be C, you save the title of C to $the_title, you’re overriding the value of B’s title

    Is the forloop done, the variable the_titleis holding the last attachment‘s title.

    Then you start to work with the value.

    Your Solution is to use the_title within the forloop.

    <?php
      $args = array( 'post_type' => 'attachment', 'posts_per_page' => 1, 'post_status' =>'any', 'post_parent' => $post->ID ); 
    
      $attachments = get_posts( $args );
      if ( $attachments) {
        foreach ( $attachments as $attachment ) {
    
             $the_title = apply_filters( 'the_title', $attachment->post_title );
             /*Use the title*/
             echo $the_title;
    
        }
      }