I've implemented a filter to my image captions based on this question I asked a few days ago. How can I slip into the caption the css style of max-width as well? I think it can be done with preg_replace, but I can't get it to work.

All I really am trying to do is force the image caption text to wrap inside the div.

The default html output looks like...

<div id="attachment_1071" style="width: 310px" class="wp-caption alignright">

I need it to look like...

<div id="attachment_1071" style="width: 310px; max-width:310px;" class="wp-caption alignright">

Here is what the filter currently looks like...

function my_caption_shortcode($atts) {
  if (isset($atts['caption'])) {
    remove_filter( current_filter(), __FUNCTION__);
    $atts['caption'] = do_shortcode($atts['caption']);
    add_filter(current_filter(), __FUNCTION__);
  //preg_replace("/width:{????}px/i", "width:{1}px; max-width:{1}px;", $atts['caption']);
  return $atts;

1 Answer 1


why not set white-space : normal ?


without seeing the rest of your css, its hard to determine why the text isn't wrapping naturally

  • I have tried that and it doesn't work. I have played around with the css a lot and the only thing that seems to work is defining the max-width of this div. I'm certainly no pro with CSS, I'm convinced it may be black magic, but I haven't found a css solution to the problem. I have a question off to the dev of the theme, but I'm not sure I will get a response.
    – Eddie
    Dec 11, 2014 at 19:10
  • could you add the css declarations for wp-caption and alignright ? That would help. Dec 11, 2014 at 22:41

Your Answer

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

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