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>';
}