It's all in the title. I'm somewhat handy with php, less so with WP hooks and subroutines. When I originally select (or later change) a featured image for a product, I want the pixel dimensions of the image written to custom fields img_w and img_l in my product record.

1 Answer 1


The key here is to use the save_post hook and have it only run the code when the post type is product (or whatever your product post type is).

Here's the code — I made the assumption that you want the full size of the featured image:

add_action( 'save_post', 'save_product_featured_image_dimensions' );

function save_product_featured_image_dimensions( $post_id ) {

    if ( get_post_type( $post_id ) != 'product' ){

    $post_thumbnail_id = get_post_thumbnail_id( $post_id );
    $attachment = wp_get_attachment_image_src( $post_thumbnail_id, 'full' );

    if ( $attachment ) {
        $width = $attachment[1];
        $height = $attachment[2];

    update_post_meta( $post_id, 'product_featured_image_width', $width );
    update_post_meta( $post_id, 'product_featured_image_height', $height );


Also, you probably know this, but it seems worth mentioning — you can of course also grab the image dimensions of a product's featured image without saving those to the metadata of the product, using code similar to the above. But I'm assuming you want to do something special that would require the values to be in the post meta.

  • 1
    Thanks, Nabha - worked perfectly, and the action and attachment code lines filled in my missing puzzle pieces. In actuality, rather than dimensions, I'm writing the aspect ratio to product custom field. That value is then used by woocommerce_dropdown_variation_attribute_options_args to dynamically filter allowable size-variants - allowing me to use one variant dataset for differently-sized products.
    – Joe Foe
    Sep 18 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.