Skip to content

Instantly share code, notes, and snippets.

@vguerrerobosch
Last active June 2, 2022 09:42
Show Gist options
  • Save vguerrerobosch/0d0641fcdacc8e5ad3618ea86ad4481c to your computer and use it in GitHub Desktop.
Save vguerrerobosch/0d0641fcdacc8e5ad3618ea86ad4481c to your computer and use it in GitHub Desktop.
WordPress image functions cheatsheet

Since WordPress function naming is an absolute mess (and so the documentation is) and after +10 years I can't manage to remember any of them, here is a quick cheatsheet I hope makes things easier in the future:

  • Display an HTML img element of the post thumbnail
the_post_thumbnail($size = 'post-thumbnail', $attr = '')
  • Get an HTML img element of the post thumbnail
get_the_post_thumbnail($post = null, $size = 'post-thumbnail', $attr = '')
  • Get the post thumbnail ID
get_post_thumbnail_id($post = null)
  • Get an HTML img element of an image attachment
wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '')
  • Get attachment image. Returns array width (string) $url, (int) $width, (int) $height, (bool) $is_resized
wp_get_attachment_image_src($attachment_id, $size = 'thumbnail', $icon = false)
  • Get attachment image URL. Uses wp_get_attachment_image_src
wp_get_attachment_image_url($attachment_id, $size = 'thumbnail', $icon = false)
  • Get attachment metadata. Returns associative array with (int) $width, (int) $height, (string) $file, (array) $sizes, (array) $image_meta
wp_get_attachment_metadata($attachment_id = 0, $unfiltered = false)
  • Get additional image sizes
wp_get_additional_image_sizes()

// by default will return an array like the following
$additional_sizes = [
    '1536x1536' => [
        'width' => 1536
        'height' => 1536
        'crop' => false
    ],
    '2048x2048' => [
        'width' => 2048
        'height' => 2048
        'crop' => false
    ],
];
  • Get an array of image sizes
get_intermediate_image_sizes()

// by default will return
$sizes = [
    'thumbnail',
    'medium',
    'medim_large',
    'large',
    '1536x1536',
    '2048x2048',
];
  • Get an associative array of image sizes keyed by name with their width, height and crop
wp_get_registered_image_subsizes()
  • Filter image sizes
add_filter('intermediate_image_sizes', function ($sizes) {
    return array_diff($sizes, [
        '1536x1536',
        '2048x2048',
    ]);
});
@mcamprecios
Copy link

mcamprecios commented May 25, 2022

Just in case!
$picture_alt = get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment