Tom
Tom

Reputation: 79

Add image title and/or description to the caption

Is it possible to manipulate the output of the image captions within the_content in such a way that not only the caption, but also the image title and/or description (defined in the media library) are output under each image?

I want to use the Data from Alt, Title, Caption AND Description in my Output

Possibly via the functions.php?

Upvotes: 2

Views: 1902

Answers (2)

Francis Li
Francis Li

Reputation: 81

Yes it is possible to manipulate the on the_content.

The easiest way which it looks like you are wanting to do is add a filter in your functions.php file.

I just pulled this from the Codex and modified a bit so you can get the gist of what I'm talking about.

add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode', 10, 3 );
 
function my_img_caption_shortcode( $output, $attr, $content ) {
    $attr = shortcode_atts( array(
        'id'      => '',
        'align'   => 'alignnone',
        'width'   => '',
        'caption' => ''
    ), $attr );
 
    if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
        return '';
    }
 
    if ( $attr['id'] ) {
        $attr['id'] = 'id="' . esc_attr( $attr['id'] ) . '" ';
    }
 
    return '<div ' . $attr['id']
    . 'class="wp-caption ' . esc_attr( $attr['align'] ) . '" '
    . 'style="max-width: ' . ( 10 + (int) $attr['width'] ) . 'px;">'
    . do_shortcode( $content )
    . '<p class="wp-caption-text">' . $attr['caption'] . '</p>'
    . '</div>';
 
}

What you can then do is if you see the $attr['caption'], you can modify how you would like it to be. So you can do: get_the_title($attr['id']) to add the title or get_post_meta($attr['id'], '_wp_attachment_image_alt', TRUE); to get the image alt.

To make things easier if you want to grab all the details on a specific attachment you can use a function like this and then get whatever you want.

Here's an example of adding the title to your caption. The format is "Title - Caption"

. '<p class="wp-caption-text">' . get_the_title($attr['id']) . " - " . $attr['caption'] . '</p>'

Link to Code reference: https://developer.wordpress.org/reference/hooks/img_caption_shortcode/

Upvotes: 1

amarinediary
amarinediary

Reputation: 5439

Maybe i'm not understanding your question but it seems to me that you're using the Gutenberg editor?
... All the features you're looking for are already built-in.

If you want to set the alt="" or title="" attributes you can do it on the right side action column, by clicking on the image itself, while in the Gutenberg editor.

enter image description here enter image description here

For the figcaption, you can set it right under the image, by clicking on the image itself, while in the Gutenberg editor.

Upvotes: 0

Related Questions