<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/* https://developer.wordpress.org/reference/hooks/post_thumbnail_html/ */
function haup_featured_image_auto_title_set( $html ) {
	//$id = get_post_thumbnail_id();
	//$attachment = get_post( $id );
	
	$thumbID = get_post_thumbnail_id();
	$attachment = get_post_meta($thumbID, '_wp_attachment_image_alt', true);

	if(isset($attachment)){
		//$at_title_text = $attachment->post_title;
		$at_title_text = $attachment;
	}else{
		$at_title_text = '';
	}

	//メディア上にaltの設定があればそれを使用、なければ投稿タイトルを取得
	if(!empty($at_title_text)){
		$title_text = $at_title_text;
	}else{
		$title_text = get_the_title();
	}

if(haup_is_single() || is_page() ){
	$html = str_replace( 'alt=', 'title="' . esc_attr( $title_text ) . '" alt=', $html );
}

	return $html;
}
add_filter( 'post_thumbnail_html', 'haup_featured_image_auto_title_set' );