如何在自定义 WordPress 主题中生成 header 图像替代文本?

How to generate header image alt text in a custom WordPress theme?

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

我写了下面的代码:

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>

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

您似乎忘记在 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" ) );  ?>

我明白了。这是我的自定义函数

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>