Show Featured Image Dimensions and size frontend with shortcode

I was wondering if I can show my featured image Dimensions (W x H in px) and the filesize in mb. In my Wordpress post with a shortcode.

thank you in advance :)

Topic shortcode php Wordpress

Category Web


Yes, that is possible. Building upon the answer Nicolai Grossherr gave to Get the size (size in Kb or MB) of an featured image? you could do something like this,

// e.g. in functions.php
add_shortcode( 'my_image_metadata', 'my_image_metadata_callback' );
function my_image_metadata_callback($atts) {
  $img_meta = wp_get_attachment_metadata( get_post_thumbnail_id() );
  if ( ! $img_meta ) {
    return;
  }

  $upload_dir = wp_upload_dir();
  $bytes = filesize(
    $upload_dir[ 'basedir' ] . DIRECTORY_SEPARATOR . $img_meta[ 'file' ]
  );
  if ( ! $bytes ) {
    return;
  }

  $file_size = size_format( $bytes );

  return sprintf(
    '<span>
      <span class="dimensions">%d x %d px</span>
      <span class="filesize">%s</span>
    </span>',
    $img_meta['width'],
    $img_meta['height'],
    $file_size ?: ''
  );
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.