Skip to content

Instantly share code, notes, and snippets.

@sou-lab
Created July 28, 2016 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sou-lab/61d4f1b2b492a2a33ef638ee35ae13ba to your computer and use it in GitHub Desktop.
Save sou-lab/61d4f1b2b492a2a33ef638ee35ae13ba to your computer and use it in GitHub Desktop.
キャプションショートコードのfigureにaria-labelledbyを、figcaptionにそのidを付ける
<?php
//キャプションにaria-labelledbyを付ける
add_shortcode('caption', 'my_img_caption_shortcode');
function my_img_caption_shortcode( $attr, $content = null ) {
// New-style shortcode with the caption inside the shortcode with the link and image tags.
if ( ! isset( $attr['caption'] ) ) {
if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
$content = $matches[1];
$attr['caption'] = trim( $matches[2] );
}
} elseif ( strpos( $attr['caption'], '<' ) !== false ) {
$attr['caption'] = wp_kses( $attr['caption'], 'post' );
}
$output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
if ( $output != '' )
return $output;
$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'] ) )
//$aria_idを追加
$aria_id = trim( 'caption-' . $atts['id'] );
$atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" ';
$class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
$html5 = current_theme_supports( 'html5', 'caption' );
// HTML5 captions never added the extra 10px to the image width
$width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
$caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
$style = '';
if ( $caption_width )
$style = 'style="width: ' . (int) $caption_width . 'px" ';
$html = '';
if ( $html5 ) {
//aria-labelledbyに$aria_idを入れる
$html = '<figure ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) .'"' . 'aria-labelledby="' . esc_attr( $aria_id ) .'">'
//figcaptionのidに$aria_idを入れる
. do_shortcode( $content ) . '<figcaption ' . 'id="' . esc_attr( $aria_id ) .'"' . 'class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
} else {
$html = '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
. do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment