0
function custom_pic_alt( $attachment_ID ) {
    
      // Get ALT
    $thumb_alt = get_post_meta( $attachment_ID, '_wp_attachment_image_alt', true );
    
    // No ALT supplied get attachment info
    if ( empty( $thumb_alt ) )
      $attachment = get_post( $attachment_ID );
    
    // Use caption if no ALT supplied
    if ( empty( $thumb_alt ) )
      $thumb_alt = get_post(get_post_thumbnail_id())->post_excerpt;
    
    // Use title if no caption supplied either
    if ( empty( $thumb_alt ) )
      $thumb_alt = get_post(get_post_thumbnail_id())->post_title;
    
    // Return ALT
    return esc_attr( trim( strip_tags( $thumb_alt ) ) );
 } 

show result

<?php echo custom_pic_alt( 10 ); ?>

and i get same alt for all attachments.

2
  • 3
    What your question describes is not what your code says, what's the purpose of the $attachment variable? It never gets used, and then for some reason you ignore everything and use get_post_thumbnail_id instead
    – Tom J Nowell
    Jan 3, 2021 at 13:33
  • Are the titles of your attachments descriptions of the content of the images? If not, you're misusing the alt attribute and making your site inaccessible to many users. Having alt="DSC_0290.JPG" might stop certain validators from complaining, but you have not actually addressed the issue. Jan 4, 2021 at 10:28

1 Answer 1

0

Not sure if this'll work for you because I don't know if $attachment_ID in the function is returning anything at all... ...but assuming it is:

function custom_pic_alt( $attachment_ID ) {
    //var_dump( $attachment_ID ); //uncomment this and see if it even returns anything.
    $thumb_alt      = get_post_meta( $attachment_ID, '_wp_attachment_image_alt', true );
    $thumb_caption  = wp_get_attachment_caption( $attachment_ID );
    $thumb_title    = get_the_title( $attachment_ID );

    if( !empty( $thumb_alt ) ) :
        $alt_text = $thumb_alt;
    elseif( empty( $thumb_alt) && !empty( $thumb_caption ) ) :
        $alt_text = $thumb_caption;
    elseif( empty( $thumb_alt ) && empty( $thumb_caption ) && !empty( $thumb_title ) ) :
        $alt_text = $thumb_title;
    else : 
        $alt_text = '';
    endif;  
    
    // Return ALT
    return esc_attr( trim( strip_tags( $alt_text ) ) );
}

You just get all three values and then run conditional checks to see if they're empty or not.

2
  • function custom_pic_alt( $attachment_ID = null ) { if ( is_null( $attachment_ID ) ) return false; // the rest of the function... }
    – Q Studio
    Jan 3, 2021 at 22:16
  • I do not need the ALT, but the TITLE and it worked great for my theme. Thank you very much!
    – Waldemar
    Aug 9, 2022 at 18:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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