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 ) ) : '' )
);?>
Currently you’re code is wrong.
In the ‘foreach’ you’re looping every
attachment
but you’re always overriding $the _title.Imagine, you have the attachments
A
,B
andC
, yourforeach
is looping over the arrayattachment
.The first element would be
A
, you save the title ofA
to$the_title
The second element would be
B
, you save the title ofB
to$the_title
, you’re overriding the value of A’s titleThe third element would be
C
, you save the title ofC
to$the_title
, you’re overriding the value of B’s titleIs the
forloop
done, the variablethe_title
is holding the lastattachment
‘s title.Then you start to work with the value.
Your Solution is to use
the_title
within theforloop
.