WooCommerce: Add-to-Cart & Remove-Links barrierefrei machen


// WooCommerce: Add-to-Cart & Remove-Links zugänglich machen (WAVE "Empty link" fix)

// 1) Produkt-Grid/Loop: <a class="add_to_cart_button">…</a> -> aria-label + SR-Text
add_filter('woocommerce_loop_add_to_cart_link', function($html, $product){
    if (! $product || ! is_a($product, 'WC_Product')) return $html;

    $label = sprintf(
        /* translators: %s product name */
        __('In den Warenkorb: %s', 'your-textdomain'),
        wp_strip_all_tags($product->get_name())
    );

    // aria-label hinzufügen, falls fehlt
    if (strpos($html, 'aria-label=') === false) {
        $html = preg_replace('/<a /', '<a aria-label="'.esc_attr($label).'" ', $html, 1);
    }

    // sichtbaren oder SR-Text sicherstellen
    if (strpos($html, 'screen-reader-text') === false) {
        $html = preg_replace(
            '/(<a [^>]*>)(.*?)(<\/a>)/',
            '$1$2<span class="screen-reader-text">'.esc_html($label).'</span>$3',
            $html,
            1
        );
    }

    return $html;
}, 10, 2);

// 2) Einzelprodukt: Button-Text hart sicherstellen (falls Theme nur Icon zeigt)
add_filter('woocommerce_product_single_add_to_cart_text', function($text){
    return $text ?: __('In den Warenkorb', 'your-textdomain');
});

// 3) Mini-Cart: „Artikel entfernen“-Link hat manchmal nur ein Icon
add_filter('woocommerce_cart_item_remove_link', function($link){
    $sr = esc_html__('Artikel entfernen', 'your-textdomain');

    // aria-label ergänzen
    if (strpos($link, 'aria-label=') === false) {
        $link = preg_replace('/<a /', '<a aria-label="'.$sr.'" ', $link, 1);
    }
    // Screenreader-Text ergänzen
    if (strpos($link, 'screen-reader-text') === false) {
        $link = preg_replace(
            '/(<a [^>]*>)(.*?)(<\/a>)/',
            '$1$2<span class="screen-reader-text">'.$sr.'</span>$3',
            $link,
            1
        );
    }
    return $link;
}, 10, 1);

// 4) Fallback-CSS für .screen-reader-text (falls Theme es überschreibt)
add_action('wp_head', function(){
    ?>
    <style>
    .screen-reader-text{
        position:absolute !important; width:1px; height:1px; padding:0; margin:-1px;
        overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; border:0;
    }
    .screen-reader-text:focus{
        clip:auto; width:auto; height:auto; margin:0; padding:.5rem;
        position:static; white-space:normal; z-index:100000;
    }
    </style>
    <?php
}, 99);