I wanted to be able to put shortcodes in an image caption. I've successfully done this by modifying the media.php file with the following just prior to return.

$atts['caption']= do_shortcode($atts['caption']);

It works great, but I'm sure there is a better approach since I would rather not modify the media.php every time I update WP.


1 Answer 1


Caption shortcode attributes are merged with defaults using shortcode_atts function like so (see source in media.php):

$atts = shortcode_atts( array(
  'id'  => '',
  'align'   => 'alignnone',
  'width'   => '',
  'caption' => '',
  'class' => '',
), $attr, 'caption' );

So the 3rd $shortcode param is in use with the value of 'caption'.

As you can see in shortcode_atts source code, it means that the filter


will be fired, allowing you to modify the attributes that will be used.

In your case you have to do something like:

add_filter("shortcode_atts_caption", function($atts) {
  if (isset($atts['caption'])) {
    $atts['caption'] = do_shortcode($atts['caption']);
  return $atts;

Please note: if the caption will contain the shortcode 'caption' this will cause an endless loop.

This can be avoided removing filter before to call do_shortcode on caption:

function my_caption_shortcode($atts) {
  if (isset($atts['caption'])) {
    // avoid endless loop
    remove_filter( current_filter(), __FUNCTION__);
    // apply shortcodes
    $atts['caption'] = do_shortcode($atts['caption']);
    // restore filter
    add_filter(current_filter(), __FUNCTION__);
  return $atts;

add_filter("shortcode_atts_caption", "my_caption_shortcode");
  • I like how you take care of the possibility that the user adds [caption] in the caption text.
    – birgire
    Commented Dec 7, 2014 at 17:01
  • Thanks @birgire :) in this specific case is not super-important, but call do_shortcode inside a shortcode callback is always dangerous...
    – gmazzap
    Commented Dec 7, 2014 at 17:04
  • Thank you very much. This answered all my questions and even some I didn't have.
    – Eddie
    Commented Dec 7, 2014 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.