I am building a custom WordPress theme without plugins. The header image for each page may be different, so I am using the dashboard to assign the image and calling the "get_header_image()" function in my theme's code. The header image is properly displayed, but the alt text is not.
I wrote the following code:
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' );
It doesn't work, probably because get_header_iamge() doesn't take arguments, right?
My HTML looks like this:
<div class="hero_container">
<img src="<?php echo( get_header_image() ); ?>" class="hero">
</div>
I set the image's alt text when I uploaded it to the media library. That text is not showing. Instead, the site's title is showing. How do I display the alt text that I set in the Media Library?
I figured it out. Here's my custom function
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' );
Here's my HTML:
<div class="hero_container">
<img src="<?php echo( get_header_image() ); ?>" alt="<?php echo( alt_text_display() ); ?>" class="hero">
</div>