Woocommerce là một plugin miễn phí được sử dụng để tạo một trang thương mại điện tử shop bán hàng trên WordPress. Tuy nhiên khi sử dụng plugin lại không có thẻ alt trong hình ảnh của sản phẩm. Đoạn code dưới đây sẽ tự động lấy title của sản phẩm làm thẻ alt cho hình ảnh:
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2); function change_attachement_image_attributes( $attr, $attachment ){ // Get post parent $parent = get_post_field( 'post_parent', $attachment); // Get post type to check if it's product $type = get_post_field( 'post_type', $parent); if( $type != 'product' ){ return $attr; } /// Get title $title = get_post_field( 'post_title', $parent); $attr['alt'] = $title; $attr['title'] = $title; return $attr; }
Chèn code trên vào functions.php của theme bạn đang sử dụng.