<?php
/*
Plugin Name: Divi Alt Text
Plugin URI: https://pavenum.com/blog/divi-alt-text-recuperation-automatique-des-alt-text-en-bibliotheque/
Description: Récupération des alt text dans la bibliothèque pour les modules Divi Image, Blurb, Slider, Fullwidth Image, Fullwidth Header, Fullwidth Slider. A partir de Divi v3.1. Please Elegant Themes fix this !
Version: 4.0
Author: Yan Thiaudière
Author URI: https://pavenum.com/
License: Free
*/


/* Récupération du alt text en bibliothèque à partir de l'URL de l'image */
function get_image_alt_text($image_url) {

	if ( ! $image_url )
		return '';
	
	if ( '/' === $image_url[0] )
		$post_id = attachment_url_to_postid(home_url() . $image_url);
	else
		$post_id = attachment_url_to_postid($image_url);
	
	$alt_text = get_post_meta($post_id, '_wp_attachment_image_alt', true);
	if ( '' === $alt_text )
		$alt_text = get_the_title($post_id);
	
	return $alt_text;

}

/* Mise à jour du alt text pour les modules concernés */
function update_module_alt_text($attrs, $unprocessed_attrs, $slug) {

	if ( ( $slug === 'et_pb_image' || $slug === 'et_pb_fullwidth_image' ) && '' === $attrs['alt'] )
		$attrs['alt'] = get_image_alt_text($attrs['src']);
	elseif ( $slug === 'et_pb_blurb' && 'off' === $attrs['use_icon'] && '' === $attrs['alt'] )
		$attrs['alt'] = get_image_alt_text($attrs['image']);
	elseif ( $slug === 'et_pb_slide' && '' !== $attrs['image'] && '' === $attrs['image_alt'] )
		$attrs['image_alt'] = get_image_alt_text($attrs['image']);
	elseif ( $slug === 'et_pb_fullwidth_header' ) {
		if ( '' !== $attrs['logo_image_url'] && '' === $attrs['logo_alt_text'] )
			$attrs['logo_alt_text'] = get_image_alt_text($attrs['logo_image_url']);
		if ( '' !== $attrs['header_image_url'] && '' === $attrs['image_alt_text'] )
			$attrs['image_alt_text'] = get_image_alt_text($attrs['header_image_url']);
	}
	
	return $attrs;
}

/* Injection du filtre */
add_filter( 'et_pb_module_shortcode_attributes', 'update_module_alt_text', 20, 3 );
