ControlledChaos
6/8/2017 - 7:12 PM

Replaces width style with max-width on the figure element of WordPress captioned images.

Replaces width style with max-width on the figure element of WordPress captioned images.

<?php

function ccd_responsive_figures_captions($dummy, $attr, $content) {
	$atts = shortcode_atts( array(
		'id'      => '',
		'align'   => 'alignnone',
		'width'   => '',
		'caption' => '',
		'class'   => '',
	), $attr, 'caption' );

	$atts['width'] = (int) $atts['width'];

	if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
		return $content;

	if ( ! empty( $atts['id'] ) )
		$atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';

	$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );

	if ( current_theme_supports( 'html5', 'caption' ) ) {
		$figure = apply_filters( 'ccd_resonsive_figures', '<figure ' . $atts['id'] . 'style="max-width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">' . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>' );
		return $figure;
	}

	return '';
}
add_filter( 'img_caption_shortcode', 'ccd_responsive_figures_captions', 10, 3 );

?>

Responsive Figure Elements

WordPress Snippet