已解决:如何在自定义WordPress主题中生成标题图像替代文本

时间:2019-07-05 17:07:12

标签: wordpress wordpress-theming accessibility alt

我正在构建没有插件的自定义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>

当我将图像的替代文本上传到媒体库时,我对其进行了设置。该文本未显示。而是显示该站点的标题。如何显示在媒体库中设置的替代文本?

2 个答案:

答案 0 :(得分: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" ) );  ?>

答案 1 :(得分:1)

我知道了。这是我的自定义功能

undefined

这是我的HTML:

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' );
相关问题