How do i upload an image and return the image id?

Take a look at side loading images. media_sideload_image()/wp_handle_sideload() and get the ID from the URL. attachment_url_to_postid.

<?php

$url = "http://wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png";
$title = "Some Image Title";
$alt_text = "Some Alt Text";

require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

// sideload the image --- requires the files above to work correctly
$src = media_sideload_image( $url, null, null, 'src' );

// convert the url to image id
$image_id = attachment_url_to_postid( $src );

if( $image_id ) {

    // make sure the post exists
    $image = get_post( $image_id );

    if( $image) {

        // Add title to image
        wp_update_post( array (
            'ID'         => $image->ID,
            'post_title' => "Some Image Title",
        ) );

        // Add Alt text to image
        update_post_meta($image->ID, '_wp_attachment_image_alt', $alt_text);
    }
}

Leave a Comment