Override The Image Caption With Image Title And Description
Here’s a way to override the caption with the image title and image description, with a demo plugin.
Let’s assume we have uploaded this image:
Then we insert it into the editor with the following:
<a href="https://example.tld/2017/03/01/hello-world/espresso/"
rel="attachment wp-att-123">
<img src="https://example.tld/wp-content/uploads/2017/03/espresso-300x180.jpg"
alt="" width="300" height="180" class="size-medium wp-image-123" />
</a> espresso caption
Before:
Without our plugin activated it will display as:
After:
With the plugin activated it displays:
Hope it helps!
Demo plugin:
We use the filters img_caption_shortcode
and shortcode_atts_caption
.
Here we wrap it into a class to pass on the attachment id between the filter callbacks.
<?php
/**
* Plugin Name: Modified Image Caption
* Description: Override The Image Caption With Image Title And Description
* Plugin URI: http://wordpress.stackexchange.com/a/258612/26350
*/
namespace WPSE\Q258586;
add_action( 'init', [ new Caption, 'init' ] );
class Caption
{
private $attachment_id ;
public function init()
{
add_filter( 'img_caption_shortcode', [ $this, 'shortcode' ], 999, 3 );
add_filter( 'shortcode_atts_caption', [ $this, 'atts' ], 999, 3 );
}
public function shortcode( $output, $attr, $content )
{
if( isset( $attr['id'] ) && preg_match( '/attachment_\d+/i', $attr['id' ] ) )
$this->attachment_id = str_replace( 'attachment_', '', $attr['id'] );
return $output;
}
public function atts( $atts, $pair )
{
if( ! $this->attachment_id )
return $atts;
$img = get_post( $this->attachment_id );
if( is_a( $img, '\WP_Post' ) )
{
$atts['caption'] = sprintf(
'<span class="title-css">%s</span>
<br><span class="description-css">%s</span>',
esc_html( $img->post_title ),
esc_html( $img->post_content )
);
}
$this->id = null;
return $atts;
}
}