<?php
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;

// BEGIN ENQUEUE PARENT ACTION
// AUTO GENERATED - Do not modify or remove comment markers above or below:

if ( !function_exists( 'chld_thm_cfg_locale_css' ) ):
    function chld_thm_cfg_locale_css( $uri ){
        if ( empty( $uri ) && is_rtl() && file_exists( get_template_directory() . '/rtl.css' ) )
            $uri = get_template_directory_uri() . '/rtl.css';
        return $uri;
    }
endif;
add_filter( 'locale_stylesheet_uri', 'chld_thm_cfg_locale_css' );

// END ENQUEUE PARENT ACTION


// Synchronisation balises alt et title avec la médiathèque, compatible WPML

add_filter('the_content', 'force_wpml_image_alt_title_sync', 100);

function force_wpml_image_alt_title_sync($content) {
    if (is_admin()) return $content;

    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $encoding = mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true);
    $dom->loadHTML('<?xml encoding="' . $encoding . '">' . $content);
    $images = $dom->getElementsByTagName('img');

    $lang = function_exists('apply_filters') ? apply_filters('wpml_current_language', null) : null;

    foreach ($images as $img) {
        $src = $img->getAttribute('src');
        if (!$src) continue;

        $original_id = attachment_url_to_postid($src);
        if (!$original_id) continue;

        // WPML : récupérer l’ID de l’image traduite
        $translated_id = function_exists('apply_filters') ?
            apply_filters('wpml_object_id', $original_id, 'attachment', false, $lang) :
            $original_id;

        if (!$translated_id) continue;

        // ALT
        $alt = get_post_meta($translated_id, '_wp_attachment_image_alt', true);
        if (!empty($alt)) {
            $img->setAttribute('alt', $alt);
        }

        // TITLE
        $title = get_the_title($translated_id);
        if (!empty($title)) {
            $img->setAttribute('title', $title);
        }
    }

    return preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());
}

