【问题标题】:How to generate header image alt text in a custom WordPress theme?如何在自定义 WordPress 主题中生成标题图像替代文本?
【发布时间】:2019-07-05 17:07:12
【问题描述】:

我正在构建一个没有插件的自定义 WordPress 主题。每个页面的标题图像可能不同,因此我使用仪表板分配图像并在我的主题代码中调用“get_header_image()”函数。标题图像正确显示,但替代文本未正确显示。

我写了以下代码:

function alt_text_display() {
    $header_id = get_header_image(get_the_ID());
    $alt = get_post_meta($header_id, 'wp_get_attachment_image_alt', true);
    echo $alt;
}

add_action( 'wp_enqueue_scripts', 'alt_text_display' );

它不起作用,可能是因为 get_header_iamge() 不接受参数,对吧?

我的 HTML 如下所示:

    <div class="hero_container">
          <img src="<?php echo( get_header_image() ); ?>" class="hero">
     </div>

我在将图片上传到媒体库时设置了图片的替代文本。该文本未显示。相反,该网站的标题正在显示。如何显示我在媒体库中设置的替代文本?

【问题讨论】:

    标签: wordpress wordpress-theming accessibility alt


    【解决方案1】:

    您好像忘记在 html 中添加“alt”属性并在其中调用函数。

    <div class="hero_container">
          <img src="<?php echo( get_header_image() ); ?>" alt="<?php display_alt_text(); ?>" class="hero">
     </div>
    

    或者你可以使用html里面的wp_get_attachment_image来输出图片:

    <?php echo wp_get_attachment_image( get_the_ID(), array('700', '600'), "", array( "alt" => "My image alt text here" ) );  ?>
    

    【讨论】:

    • 你好阿图拉斯。谢谢你的回复。在主题代码中添加 alt 标签将覆盖我在将图像上传到媒体库时应用到图像的 alt 文本。我知道我的问题本来可以更清楚。
    【解决方案2】:

    我想通了。这是我的自定义函数

    function alt_text_display() {
    
            $data =  get_object_vars(get_theme_mod('header_image_data'));
            $image_id = is_array($data) && isset($data['attachment_id']) 
                        ? $data['attachment_id'] : false;
    
            if ($image_id) {
    
                $image_alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true);
                return image_alt;
    
            }
    
        }
    
        add_action( 'wp_enqueue_scripts', 'alt_text_display' );
    

    这是我的 HTML:

    <div class="hero_container">
                        <img src="<?php echo( get_header_image() ); ?>" alt="<?php echo( alt_text_display() ); ?>"  class="hero">
                    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多