Show File Type and Size on Document Links
Adds the file type and size, such as "(PDF, 2.4 MB)", after links to PDF, Word, Excel and PowerPoint files in your content, so visitors know what they are about to download.
Opens WPIDE on
Code
// Extensions to label, with the name shown to visitors.
$wpide_doc_types = array(
'pdf' => 'PDF',
'doc' => 'Word',
'docx' => 'Word',
'xls' => 'Excel',
'xlsx' => 'Excel',
'ppt' => 'PowerPoint',
'pptx' => 'PowerPoint',
'zip' => 'ZIP',
);
add_filter( 'the_content', function ( $content ) use ( $wpide_doc_types ) {
$pattern = '#<a\b([^>]*\bhref=["\']([^"\']+\.(' . implode( '|', array_keys( $wpide_doc_types ) ) . '))(?:\?[^"\']*)?["\'][^>]*)>(.*?)</a>#is';
if ( ! preg_match( '#\.(' . implode( '|', array_keys( $wpide_doc_types ) ) . ')\b#i', $content ) ) {
return $content;
}
$uploads = wp_get_upload_dir();
return preg_replace_callback( $pattern, function ( $m ) use ( $wpide_doc_types, $uploads ) {
if ( false !== strpos( $m[4], 'wpide-file-info' ) ) {
return $m[0];
}
$type = $wpide_doc_types[ strtolower( $m[3] ) ];
$info = $type;
$url = set_url_scheme( $m[2], 'https' );
$base = set_url_scheme( $uploads['baseurl'], 'https' );
if ( 0 === strpos( $url, $base ) ) {
$path = $uploads['basedir'] . substr( $url, strlen( $base ) );
if ( false === strpos( $path, '..' ) && is_readable( $path ) ) {
$info .= ', ' . size_format( filesize( $path ), 1 );
}
}
return '<a' . $m[1] . '>' . $m[4] . ' <span class="wpide-file-info">(' . esc_html( $info ) . ')</span></a>';
}, $content );
}, 20 );
Notes
The size is only shown for files stored in your uploads folder; links to other sites get the file type only.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.