首页 > 解决方案 > img_caption_shortcode 的实现没有效果

问题描述

我在孩子的functions.php中添加了以下代码

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

    if ( 1 > (int) $attr['width'] || empty( $attr['caption'] ) ) {
        return '';
    }

    if ( $attr['id'] ) {
        $attr['id'] = 'id="' . esc_attr( $attr['id'] ) . '" ';
    }

    return '<div ' . $attr['id']
    . 'class="wp-caption ' . esc_attr( $attr['align'] ) . '" '
    . 'style="max-width: ' . ( 10 + (int) $attr['width'] ) . 'px;">'
    . do_shortcode( $content )
    . '<p class="wp-caption-text">TEST TEST' . $attr['caption'] . '</p>'
    . '</div>';
}

尽管如此,the_content 中的所有图像都会在帖子中输出,如下所示:

<figure class="wp-block-image size-large"><img loading="lazy" width="960" height="637" src="https://www.example.com/img.jpg" alt="example" class="wp-image-9987" srcset=" (...) "><figcaption>My caption text</figcaption></figure>

上面的钩子似乎没有任何效果

使用 the_content() 在 single.php 中读取帖子的内容。

标签: wordpresswordpress-theming

解决方案


尝试确保img_caption_shortcode()正在调用该函数。在我们的例子中,几年前有人添加了自定义短代码处理程序,而自定义处理程序没有应用img_caption_shortcode过滤器。


推荐阅读