donnamcmaster
3/15/2017 - 4:47 AM

WordPress: set a title attribute in gallery output; some plugins will display this as a caption

WordPress: set a title attribute in gallery output; some plugins will display this as a caption

<?php
/**
*    Add Title Field
*    - adds image caption to image tags; will show up as gallery captions
*    - this example uses image caption if defined, with fallback to post title
*    - edit as desired to choose post title, description, or caption (excerpt) 
*/
add_filter( 'wp_get_attachment_link', function( $anchor, $id ) {
    $_post = get_post( $id );
    if ( !$_post ) {
        return $anchor;
    }
    $title = $_post->post_excerpt; // caption
    $title = $title ? $title : $_post->post_title; // actual title
//    $title_tag = $_post->post_content; // description
    $title = esc_html( $title );
    $anchor = str_replace( 'href', "title='$title' href", $anchor );
    return $anchor;
}, 10, 2 );