如何设置特色图片的Alt&TITLE Get_the_Post_Thumb(获取缩略图)

时间:2020-05-07 作者:javadth

我想在此代码中设置alt和title属性的帖子标题

我该怎么办?

<?php
if ( true == get_theme_mod( \'archive_featured_images\', true ) ) :
    if ( has_post_thumbnail() && ( get_the_post_thumbnail() != \'\' ) ) :
        echo \'<a class="featured-image" href="\'. esc_url( get_permalink() ) .\'" title="\'. the_title_attribute( \'echo=0\' ) .\'">\';
        echo \'<span itemprop="image" itemscope itemtype="https://schema.org/ImageObject">\';
        the_post_thumbnail( \'mudra-featured-image\' );
        $mudra_image = wp_get_attachment_image_src( get_post_thumbnail_id(), \'mudra-featured-image\' );
        echo \'<meta itemprop="url" content="\' . esc_url( $mudra_image[0] ) . \'">\';
        echo \'<meta itemprop="width" content="\' . esc_attr( $mudra_image[1] ) . \'">\';
        echo \'<meta itemprop="height" content="\' . esc_attr( $mudra_image[2] ) . \'">\';
        echo \'</span>\';
        echo \'</a>\';
    endif;
endif;
?>

1 个回复
SO网友:Aboelabbas

您可以使用的第二个参数the_post_thumbnail() 作用

the_post_thumbnail( \'mudra-featured-image\', [\'alt\' => get_the_title()] );
另一个选项是,您可以使用过滤器执行此操作wp_get_attachment_image_attributes

add_filter(\'wp_get_attachment_image_attributes\', function($attr){
    $attr[\'alt\'] = get_the_title();
    return $attr;
});
注意,使用过滤器将影响使用任何函数打印的其他图像,这些函数取决于wp_get_attachment_image()

因此,您可以使用传递给回调函数的其他两个属性来进行更多控制。例如,如果您只想在大小为“mudra featured image”的图像上应用此选项,那么您的代码如下所示

add_filter( \'wp_get_attachment_image_attributes\', function( $attr, $attachment, $size ){

    // Return the current $attr array as it is if the size is not "mudra-featured-image"
    if( \'mudra-featured-image\' !== $size ){
        return $attr;
    }
    // If it is our targeted size then, change the "alt" attribute
    $attr[\'alt\'] = get_the_title();
    return $attr;

}, 10, 3 );