Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using a custom header in my theme. My aim is to add an alt attribute to my custom header img element. My img element so far looks like this:

<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />

How can I get the alt text of the custom header image?

share|improve this question
    
Interesting question, one would expect this to be available with get_custom_header()->alt, but that's not the case, as far as I can see after skimming through the source ;-) But fortunately @TheDeadMedic found a great work around. –  birgire Jun 26 at 11:00
    
My thoughts exactly regarding get_custom_header()->alt. Thanks to @TheDeadMedic for the solution. –  henrywright Jun 26 at 11:34

1 Answer 1

up vote 4 down vote accepted
/**
 * Get custom header's alt data.
 * 
 * @link    http://wordpress.stackexchange.com/q/151850/1685
 * 
 * @return  string
 */
function wpse_151850_get_header_image_alt() {
    $attachment_id = 0;

    if ( is_random_header_image() && $header_url = get_header_image() ) {
        // For a random header, we have to search for a match against all headers.
        foreach ( get_uploaded_header_images() as $header ) {
            if ( $header['url'] == $header_url ) {
                $attachment_id = $header['attachment_id'];
                break;
            }
        }

    } elseif ( $data = get_custom_header() ) {
        // For static headers, less intensive approach.
        $attachment_id = $data->attachment_id;
    } 

    if ( $attachment_id ) {
        $alt = trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) );

        if ( ! $alt ) // Fallback to caption (excerpt)
            $alt = trim( strip_tags( get_post_field( 'post_excerpt', $attachment_id ) ) );
        if ( ! $alt ) // Fallback to title
            $alt = trim( strip_tags( get_post_field( 'post_title', $attachment_id ) ) );
    } else {
        $alt = '';
    }

    return $alt;
}
share|improve this answer
    
One slight modification I'd make to your function is the use of get_custom_header()->attachment_id to get the static header attachment ID instead of $data = get_theme_mod( 'header_image_data' ). Your function then works perfectly. –  henrywright Jul 14 at 11:52
    
Nice touch, done. –  TheDeadMedic Jul 14 at 15:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.