【问题标题】:Add image title and/or description to the caption将图像标题和/或描述添加到标题
【发布时间】:2021-01-07 15:01:49
【问题描述】:

是否可以在 the_content 中以这样的方式操作图像标题的输出,不仅标题,而且图像标题和/或描述(在媒体库中定义)在每张图片下输出?

可能通过functions.php?

【问题讨论】:

  • 你现在有输出的例子吗?
  • 当然。 the_content 中的图片类似于<div class="wp-block-image"><figure class="alignleft size-large is-resized"><img src="https://www.example.com/wp-content/uploads/winter.jpg" alt="Correct Alt Text" width="400"></figure></div>
  • 谢谢你想要的输出是什么?
  • 我正在寻找一种方法来操纵图像在“the_content”中显示的形式。例如作为一个包含
    。然后我想不仅输出定义的标题本身,还输出图像标题/图像描述(也在 WP 媒体库中定义)。

标签: wordpress wordpress-theming


【解决方案1】:

是的,可以操纵the_content

看起来你想要做的最简单的方法是在你的functions.php文件中添加一个过滤器。

我刚刚从 Codex 中提取了这个并稍作修改,以便您了解我在说什么。

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">' . $attr['caption'] . '</p>'
    . '</div>';
 
}

然后您可以做的是,如果您看到$attr['caption'],您可以修改您想要的样子。所以你可以这样做:get_the_title($attr['id']) 添加标题或get_post_meta($attr['id'], '_wp_attachment_image_alt', TRUE); 获取图像替代。

如果您想获取特定附件的所有详细信息,可以使用 this 之类的函数,然后获取您想要的任何内容。

这是一个将标题添加到标题的示例。格式为“Title - Caption”

. '<p class="wp-caption-text">' . get_the_title($attr['id']) . " - " . $attr['caption'] . '</p>'

代码参考链接:https://developer.wordpress.org/reference/hooks/img_caption_shortcode/

【讨论】:

    【解决方案2】:

    也许我不理解您的问题,但在我看来您使用的是 Gutenberg 编辑器?
    ...您正在寻找的所有功能都已内置。

    如果您想设置 alt=""title="" 属性,您可以在右侧的操作列中进行,方法是在古腾堡编辑器中单击图像本身。

    对于figcaption,您可以在图像下方设置它,方法是在古腾堡编辑器中单击图像本身。

    【讨论】:

    • 我已经更新了我的问题,以便更好地理解它。是的,我使用块编辑器,但我不仅要输出 ALT 和 CAPTION,还要输出图像的 TITLE 和DESCRIPTION(在媒体库中定义)
    • 而不是您通常在编辑器中定义的那个?
    • 是的,我想使用functions.php 来确定应该如何在“the_content”中输出图像。主题是自行开发的。
    猜你喜欢
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    相关资源
    最近更新 更多