The site im working on has a shortcode function to display image captions, credits and date, but if the caption is not set that function does not work.

I created a function to add credits/date when they are set and caption is not. My problem is if a caption is set afterwards i get the html from both functions causing it to be duplicated.

Code:

    function include_image_credits( $html, $id, $alt, $title, $align, $size ) {
        $caption = wp_get_attachment_caption( $id );
        $get_img_info = wp_get_attachment_metadata( $id );
        $img_width = $get_img_info['width'];
        $credits = get_post_meta( $id, 'photographer_name', true );
        $date = get_post_meta( $id, 'photo_date',true );
        $styles = '';
    if ( $img_width ) {
            $styles = 'style="width: ' . (int) $img_width . 'px" ';
    }

    if ( isset( $credits ) && empty( $caption ) && '' !== $credits || isset( $date ) &&  empty( $caption ) && '' !== $date ) {
            $html .= '<div class="credits__date"' . $styles . '>' ;
            $html .= '<span class="caption__source">' . $credits . '</span> ';
            $html .= '<span class="caption__date">' . $date . '</span> ';
            $html .= '</div> <br />';
    }
    return $html;
}
add_filter( 'get_image_tag', 'include_image_credits', 10, 6 );

Is there a way to delete the html from this function if a caption is set later?

Read more here: Remove html after condition changes


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: