0

I want to add the caption ALWAYS to images, even if it is empty. This is my function to add the caption, but the caption element will not be generated when there is no content in it, how to add the caption element always?

add_filter('img_caption_shortcode', 'caption_shortcode_inline_text', 10, 3);
function caption_shortcode_inline_text($empty, $attr, $content) {
extract(shortcode_atts(array(
    'id'    => '',
    'align' => 'alignnone',
    'width' => '',
    'caption' => ''
), $attr));

// in this part I amtrying to always add the caption element but it doesn't work:

if (1 < (int) $width || 1 > (int) $width || $caption || !$caption)
    return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">'
    . do_shortcode($content) . '<p class="wp-caption-text">' . $caption . '</p></div>';
}
  • if (1 < (int) $width || 1 > (int) $width ) this will only consider the width property. – GrafiCode Oct 17 '15 at 14:07
  • This doesn't work, too: "if ($caption || !$caption)" – Henning Fischer Oct 17 '15 at 14:09
  • that statement will always return true :) did you try to check the width parameter? because your condition is basically if ( (int) $width != 1 ) { .... } – GrafiCode Oct 17 '15 at 14:16
  • I don't know id I understand you right - I want the condition always to return true. Because i always want to show the caption element, even when it is emtpy. – Henning Fischer Oct 17 '15 at 14:23
  • 1
    you could simply remove the IF and let it return sistematically – GrafiCode Oct 17 '15 at 14:27
0

This works:

add_filter( 'disable_captions', create_function('$a', 'return true;') );
function image_send_to_editor_2($html, $id, $caption, $title, $align, $url, $size, $alt) {

    $width = 'auto';

    if ( preg_match( '/width="([0-9]+)/', $html, $matches ) ) {
        $width = $matches[1] . 'px';
    }

    $output = '<div id="attachment-' . $id . '" class="wp-caption align' . $align . '" style="width: ' . $width . ';">';
    $output .= $html;
    $output .= '<p class="wp-caption-text">' . $caption . '</p>';
    $output .= '</div>';
    return $output;

}

add_filter('image_send_to_editor', 'image_send_to_editor_2', 10, 8);
  • 1
    It would be helpful to add some description on how the code works, thanks – birgire Oct 17 '15 at 17:58
  • The caption is just disabled and a new one is created. – Henning Fischer Oct 17 '15 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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