Skip to content

Instantly share code, notes, and snippets.

@JoostKiens
Last active April 22, 2019 09:58
Show Gist options
  • Save JoostKiens/4477366 to your computer and use it in GitHub Desktop.
Save JoostKiens/4477366 to your computer and use it in GitHub Desktop.
Improve the WordPress caption shortcode with HTML5 figure & figcaption, microdata & wai-aria attributes
<?php
/**
* Improves the WordPress caption shortcode with HTML5 figure & figcaption, microdata & wai-aria attributes
*
* Author: @joostkiens
* Licensed under the MIT license
*
* @param string $val Empty
* @param array $attr Shortcode attributes
* @param string $content Shortcode content
* @return string Shortcode output
*/
function my_img_caption_shortcode_filter( $val, $attr, $content = null ) {
extract( shortcode_atts( array(
'id' => '',
'align' => 'aligncenter',
'width' => '',
'caption' => ''
), $attr ) );
// No caption, no dice...
if ( 1 > (int) $width || empty( $caption ) )
return $val;
if ( $id )
$id = esc_attr( $id );
// Add itemprop="contentURL" to image - Ugly hack
$content = str_replace('<img', '<img itemprop="contentURL"', $content);
return '<figure id="' . $id . '" aria-describedby="figcaption_' . $id . '" class="wp-caption ' . esc_attr($align) . '" itemscope itemtype="http://schema.org/ImageObject" style="width: ' . (0 + (int) $width) . 'px">' . do_shortcode( $content ) . '<figcaption id="figcaption_'. $id . '" class="wp-caption-text" itemprop="description">' . $caption . '</figcaption></figure>';
}
add_filter( 'img_caption_shortcode', 'my_img_caption_shortcode_filter', 10, 3 );
@SimonFricker
Copy link

Thank you so much for this. How do I remove Height and Width defined in the IMG tag by Wordpress?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment