J'utilise un en-tête personnalisé dans mon thème. Mon objectif est d'ajouter un attribut alt
à mon élément img
d'en-tête personnalisé. Mon élément img
ressemble jusqu'ici à ceci:
<img src="<?php header_image(); ?>" height="<?php echo get_custom_header()->height; ?>" width="<?php echo get_custom_header()->width; ?>" alt="" />
Comment puis-je obtenir le texte de remplacement de l'image d'en-tête personnalisé?
/**
* 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;
}
Ok j'ai trouvé la réponse que personne n'a sur le net que je cherchais depuis plusieurs jours.
Voici comment j'ai pu le faire. J'espère que cela aide quelqu'un là-bas
// This is getting the image / url
$feature1 = get_theme_mod('feature_image_1');
// This is getting the post id
$feature1_id = attachment_url_to_postid($feature1);
// This is getting the alt text from the image that is set in the media area
$image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );
Markup
<a href="<?php echo $feature1_url; ?>"><img class="img-responsive center-block" src="<?php echo $feature1; ?>" alt="<?php echo $image1_alt; ?>"></a>