When cropping a header image, retain meta data (i.e. name, description, etc.) from original image?

Here’s one idea, that might need further testing:

/**
 * Cropped header image with the same description/caption as the original image
 */
add_filter( 'wp_create_file_in_uploads', function( $cropped, $attachment_id )
{
    add_filter( 'wp_insert_attachment_data', function( $data ) use ( $attachment_id)
    {
        if( doing_action( 'wp_ajax_custom-header-crop' ) && is_array( $data ) )
        {
            // Copy the original description to the cropped image
            $data['post_content'] = get_post_field( 'post_content', $attachment_id, 'db' );
            // Copy the original caption to the cropped image
            $data['post_excerpt'] = get_post_field( 'post_excerpt', $attachment_id, 'db' );
        }
        return $data;
    } );
    return $cropped;
}, 10, 2 );

Here we copy the description and caption from the original image through the wp_create_file_in_uploads and wp_insert_attachment_data filters. To restrict it in the context of the custom header ajax crop, we check it with:

 doing_action('wp_ajax_custom-header-crop')` 

Here we also pass on the $attachment_id, of the original image, into the closure with the help of the use keyword.

If we need to copy the image meta as well, then we could use a similar approach through the wp_header_image_attachment_metadata filter:

/**
 * Cropped header image with the same image meta as the original one
 */
add_filter( 'wp_create_file_in_uploads', function( $cropped, $attachment_id )
{
    add_filter( 'wp_header_image_attachment_metadata', function( $metadata ) use ( $attachment_id )
    {
        if( doing_action( 'wp_ajax_custom-header-crop' ) && isset( $metadata['image_meta'] ) )
        {
            // Fetch the image meta of the original image
            $original_metadata = wp_get_attachment_metadata( $attachment_id );
            // Copy the original image meta data for the cropped image
            if( is_array( $original_metadata['image_meta'] ) )
                $metadata['image_meta'] = $original_metadata['image_meta'];
        }       
        return $metadata;
    } );
    return $cropped;
}, 10, 2 );

Hope you can adjust it to your needs.

Leave a Comment