繁体   English   中英

在WordPress中显示图片库中向数组添加ALT标签

[英]Add ALT tag to the array in displaying image gallery in WordPress

如何为这些图像添加ALT标签? 我必须添加

$alt = get_post_meta(get_post_thumbnail_id($post->ID), '_wp_attachment_image_alt', true);

到数组,然后添加<?php echo $alt; ?> <?php echo $alt; ?>显示图像时?

  <?php /* 2 IMAGES DIVIDER */ ?>
    <?php if($divider_type == 'images'): ?>
    <section class='divider content gallery'>
        <?php 
        $images = array();
        foreach($section['images'] as $image_id => $image_url)
        {
            $image = wp_get_attachment_image_src($image_id, '900w');
            $image_details = get_post($image_id);
            $images[] = array('img_url'=>$image[0],'caption'=>$image_details->post_excerpt);
        }
        ?>
        <div class='gallery-half'>
            <figure>
                <img src='<?php echo $images[0]['img_url']; ?>'>
                <?php if($images[0]['caption'] != ''): ?>
                <figcaption><?php echo $images[0]['caption']; ?></figcaption>
                <?php endif; ?>
            </figure>
        </div><!--
        --><div class='gallery-half'>
            <img src='<?php echo $images[1]['img_url']; ?>'>
        </div>
    </section>
    <?php endif; ?>

先感谢您。

为什么不使用wp_get_attachment_image() 这会为您处理alt标签。

<?php /* 2 IMAGES DIVIDER */ ?>
<?php if ( $divider_type == 'images' ) : ?>
    <section class='divider content gallery'>
        <?php 
        $images = array();
        foreach ( $section['images'] as $image_id => $image_url ) : ?>
            <?php $image_details = get_post( $image_id ); ?>
            <div class='gallery-half'>
                <figure>
                    <?php echo wp_get_attachment_image( $image_id, '900w' ); ?>
                    <?php if ( $image_details->post_excerpt ) : ?>
                        <figcaption><?php echo $image_details->post_excerpt; ?></figcaption>
                    <?php endif; ?>
                </figure>
            </div>
       <?php endif; ?>
    </section>
<?php endif; ?>

我对代码段进行了一些修改,以便它将循环遍历$ section ['images']中的所有图像,并在.gallery-half div div中输出带有Figure元素和标题(如果有的话)的图片。

您也可以使用wp_get_attachment_image ,它将为您提供带有alt属性的img html标签。 但是,您是对的,如果要自己获取值,则必须使用get_post_meta 实际上, wp_get_attachment_image函数执行相同的操作以访问该数据。

$default_attr = array(
    'src'   => $src,
    'class' => "attachment-$size_class size-$size_class",
    'alt'   => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM