2

I want a simple function to display image titles and captions alongside each other below the images on wordpress posts and pages. All the answers I have seen do not work for me. Either they leave the title blank or show the post/page title instead of the image title.

This is what I have tried so far.

 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">' . get_the_title($image_id) . ", " . $attr['caption'] . '</p>' . '</div>'; } 

1 Answer 1

3

you are trying to get the image title using get_the_title($image_id), but $image_id is not defined in your function. Instead, you should use the id attribute provided in the shortcode attributes.

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 ''; } // Get the image ID from the shortcode ID attribute $image_id = isset( $attr['id'] ) ? (int) $attr['id'] : 0; // Get the image title $image_title = get_post( $image_id )->post_title; 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">' . $image_title . ", " . $attr['caption'] . '</p>' . '</div>'; } 
1
  • Thanks for the help but this shows the post title and not the image title. Commented Mar 1, 2024 at 8:38

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.