Add extra class to wp-caption?

How do you add a new class to the HTML generated when an image with captions is added?

For example, from this:

<div id="attachment_xyz" class="wp-caption alignleft"...

to this:

<div id="attachment_xyz" class="wp-caption alignleft my_new_class"...

Adding, in this case, my_new_class.

Thanks, Scott

2 Answers
2

Adapted from this answer

Add this code to your functions.php file:

add_action( 'after_setup_theme', 'wpse_74735_replace_wp_caption_shortcode' );

/**
 * Replace the default caption shortcode handler.
 *
 * @return void
 */
function wpse_74735_replace_wp_caption_shortcode() {
    remove_shortcode( 'caption', 'img_caption_shortcode' );
    remove_shortcode( 'wp_caption', 'img_caption_shortcode' );
    add_shortcode( 'caption', 'wpse_74735_caption_shortcode' );
    add_shortcode( 'wp_caption', 'wpse_74735_caption_shortcode' );
}

/**
 * Add the new class to the caption.
 *
 * @param  array  $attr    Shortcode attributes
 * @param  string $content Caption text
 * @return string
 */
function wpse_74735_caption_shortcode( $attr, $content = NULL )
{
    $caption = img_caption_shortcode( $attr, $content );
    $caption = str_replace( 'class="wp-caption', 'class="wp-caption my_new_class', $caption );
    return $caption;
}

Leave a Comment