How to get the image EXIF date/time and use it for the WP post date/time

PHP has a function for this purpose: exif_read_data
I used this image for testing.
Try this code for your purpose:

add_action( 'add_attachment', 'create_post_from_image' );
function create_post_from_image( $id ) {
    if ( wp_attachment_is_image( $id ) ) {
        $image = get_post( $id );
        // Get image height/width for auto inserting the image later
        @list( $width, $height ) = getimagesize( get_attached_file( $id ) );

        $post = array(
            // Set image title as post title
            'post_title'   => $image->post_title,
            // Set post to draft for details
            'post_status'  => 'draft',
            // "Fake" WordPress insert image code
            'post_content' => '<a href="' . $image->guid . 
                '"><img class="alignnone size-full wp-image-' . $image->ID . 
                '" src="' . $image->guid . '" alt="' . $image->post_name . 
                '" width="' . $width . '" height="' . $height . '" /></a>'
        );

        // Take image date 
        if ( function_exists( 'exif_read_data' ) ) {
            $exif = exif_read_data( $image->guid );
            if ( ! empty( $exif['DateTime'] ) ) {
                //var_dump( $exif['DateTime'] );
                $post['post_date'] = $exif['DateTime'];
            }
        }

        $postid = wp_insert_post( $post );
        if ( $postid ) {
            // Set image as post featured image
            set_post_thumbnail( $postid, $image->ID );
            // Attach image to the post
            wp_update_post( array(
                'ID'          => $id,
                'post_parent' => $postid
            ) );
        }
    }
}

Leave a Comment

error code: 523