I need to import images from an url and return the image id

is it possible to make a function like this?

    <?php
$link = 'https://mosaic01.ztat.net/vgs/media/pdp-zoom/NI/11/3D/03/4D/11/NI113D034-D11@12.jpg';
$title="the image title";
$alt="the image alt";

$image_id = insert_image($link, $title, $alt);

?>

2 Answers
2

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 Reply

Your email address will not be published. Required fields are marked *