Skip to content

Instantly share code, notes, and snippets.

@JulioPotier
Last active December 3, 2019 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JulioPotier/5238fd962059ddf590dfefca72e02434 to your computer and use it in GitHub Desktop.
Save JulioPotier/5238fd962059ddf590dfefca72e02434 to your computer and use it in GitHub Desktop.
media to shortcode
function human_filesize( $bytes, $decimals = 2 ) {
$sz = 'BKMGTP';
$factor = floor( ( strlen( $bytes ) - 1 ) / 3 );
return sprintf( "%.{$decimals}f", $bytes / pow( 1024, $factor ) ) . @$sz[ $factor ];
}
add_filter( 'media_send_to_editor', 'baw_media_to_shortcode', 10, 3 );
function baw_media_to_shortcode( $html, $id, $attachment ) {
$media_type = strtolower( pathinfo( $attachment['url'], PATHINFO_EXTENSION ) );
switch ( $media_type ) {
case 'jpg':
case 'jpeg':
case 'png':
return sprintf( '[img id="%s" size="%s"]',
$id,
$attachment['image-size']
);
break;
case 'pdf':
case 'doc':
case 'docx':
case 'xls':
case 'xlsx':
return sprintf( '[file id="%s"]',
$id
);
break;
default:
return $html;
break;
}
}
add_shortcode( 'img', 'baw_img_sc_cb' );
function baw_img_sc_cb( $atts, $content = '' ) {
$atts = shortcode_atts( [ 'id' => '', 'size' => 'thumbnail' ], $atts, 'img' );
return wp_get_attachment_link( $atts['id'], $atts['size'] );
}
add_shortcode( 'file', 'baw_file_sc_cb' );
function baw_file_sc_cb( $atts, $content = '' ) {
$atts = shortcode_atts( [ 'id' => '', 'size' => 'thumbnail' ], $atts, 'file' );
add_filter( 'wp_get_attachment_link', 'baw_file_add_filesize', 10, 2 );
$pdf_link = wp_get_attachment_link( $atts['id'], $atts['size'] );
remove_filter( 'wp_get_attachment_link', 'baw_file_add_filesize', 10, 2 );
return $pdf_link;
}
function baw_file_add_filesize( $html, $id ) {
$_post = get_post( $id );
$attached_file = get_post_meta( $_post->ID, '_wp_attached_file', true );
if ( $attached_file ) {
$ext = pathinfo( $attached_file, PATHINFO_EXTENSION );
$base = pathinfo( $attached_file, PATHINFO_BASENAME );
$uploads = wp_get_upload_dir();
$filesize = human_filesize( filesize( $uploads['basedir'] . '/' . $attached_file ) );
$html = str_replace( '</a>', sprintf( '<em>%s %s %s</em></a>', $base, $filesize, $ext ), $html );
}
return $html;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment