Skip to content

Instantly share code, notes, and snippets.

@hereswhatidid
Created August 16, 2013 15:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hereswhatidid/6250884 to your computer and use it in GitHub Desktop.
Save hereswhatidid/6250884 to your computer and use it in GitHub Desktop.
Add a custom attribute to the 'caption' shortcode
<?php
/**
* Add custom attribute to the 'caption' shortcode
*
* ex:
* [caption id="attachment_883" align="alignnone" width="259" use_figure="yes"]<a href="image.jpg"><img class="size-full wp-image-883" alt="This is a caption." src="image.jpg" width="259" height="195" /></a> This is a caption.[/caption]
*
* @param array $out The output array of shortcode attributes
* @param array $pairs The array of accepted parameters and their defaults
* @param array $atts The input array of shortcode attributes
*/
function add_custom_caption_attribute( $out, $pairs, $atts ) {
$out['use_figure'] = '';
return $out;
}
add_filter( 'shortcode_atts_caption', 'add_custom_caption_attribute', 10, 3 );
/**
* Detect if the 'use_figure' custom attribute has been set to 'yes'
* If so, output a figure/figcaption elemente rather than the default
* div format
*
* @param string $input Blank string
* @param array $atts Shortcode attributes
* @param string $content Content within the shortcode wrappers
* @return string Formatted output
*/
function override_caption_shortcode( $input, $atts, $content ) {
if( isset( $atts['use_figure'] ) && 'yes' == $atts['use_figure'] ) {
extract(shortcode_atts(array(
'id' => '',
'align' => 'alignnone',
'width' => '',
'caption' => ''
), $atts, 'caption'));
if ( 1 > (int) $width || empty($caption) )
return $content;
if ( $id ) $id = 'id="' . esc_attr($id) . '" ';
return '<figure ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
. do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $caption . '</figcaption></figure>';
}
}
add_filter( 'img_caption_shortcode', 'override_caption_shortcode', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment