"" ; "red-front-door" -> "Red front door". */
public static function alt_from_filename( $name ) {
$base = pathinfo( (string) $name, PATHINFO_FILENAME );
$base = preg_replace( '/-\d+x\d+$/', '', $base );
$base = trim( preg_replace( '/[\s_\-]+/', ' ', $base ) );
if ( '' === $base || preg_match( '/^(img|dsc|dscn|image|photo|screenshot|pxl|whatsapp|untitled)?\s*[\d\s]*$/i', $base ) || preg_match( '/^[0-9a-f]{8,}$/i', $base ) ) {
return '';
}
return ucfirst( $base );
}
public static function alt_for_attachment( $att_id, $fallback = '' ) {
$alt = trim( (string) get_post_meta( $att_id, '_wp_attachment_image_alt', true ) );
if ( '' !== $alt ) {
return $alt;
}
$title = trim( (string) get_the_title( $att_id ) );
$guess = self::alt_from_filename( $title ) ?: self::alt_from_filename( get_attached_file( $att_id ) );
return $guess ?: $fallback;
}
public static function attrs( $attr, $attachment ) {
if ( ! empty( $attr['alt'] ) ) {
return $attr;
}
$parent = $attachment->post_parent ? get_the_title( $attachment->post_parent ) : get_the_title();
$alt = self::alt_for_attachment( $attachment->ID, (string) $parent );
if ( $alt ) {
$attr['alt'] = $alt;
}
return $attr;
}
public static function thumb_html( $html, $post_id ) {
return self::fix_tags( $html, get_the_title( $post_id ) );
}
public static function content( $content ) {
if ( is_admin() || ! in_the_loop() && ! is_singular() ) {
return $content;
}
return self::fix_tags( $content, get_the_title() );
}
private static function fix_tags( $html, $fallback ) {
if ( false === stripos( $html, '
]*>#i',
function ( $m ) use ( $fallback ) {
$tag = $m[0];
if ( preg_match( '#\balt=(["\'])(.*?)\1#is', $tag, $a ) && '' !== trim( $a[2] ) ) {
return $tag;
}
$alt = '';
if ( preg_match( '#wp-image-(\d+)#', $tag, $id ) ) {
$alt = self::alt_for_attachment( (int) $id[1], $fallback );
} elseif ( preg_match( '#\bsrc=["\']([^"\']+)["\']#i', $tag, $s ) ) {
$alt = self::alt_from_filename( wp_parse_url( $s[1], PHP_URL_PATH ) ) ?: $fallback;
}
if ( '' === $alt ) {
return $tag;
}
if ( preg_match( '#\balt=(["\'])\1#i', $tag ) ) {
return preg_replace( '#\balt=(["\'])\1#i', 'alt="' . esc_attr( $alt ) . '"', $tag, 1 );
}
return preg_replace( '#![' . esc_attr( $alt ) . ']()