How to Insert images in WordPress using code

You can try the following function to insert image to a post.

Note: The following function will not make the image “featured image”. It will just uploaded the image and attach it to the post.

It will return the attachment id if the upload is successful

function insert_post_media( $post_id, $url){

        $tmp = download_url( $url );

        $file_array = array();

        // Set variables for storage
        // fix file filename for query strings
        preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
        $file_array['name'] = basename($matches[0]);
        $file_array['tmp_name'] = $tmp;

        // If error storing temporarily, unlink
        if ( is_wp_error( $tmp ) ) {
            @unlink($file_array['tmp_name']);
            $file_array['tmp_name'] = '';
        }

        // do the validation and storage stuff
        $id = media_handle_sideload( $file_array, $post_id, $desc );

        // If error storing permanently, unlink
        if ( is_wp_error($id) ) {
            @unlink($file_array['tmp_name']);
            $error_string = $id->get_error_message();
            echo '<div id="message" class="error">'.$url.'<p>' . $error_string . '</p></div>';
            return $id;
        }

        return $id;            

        //incase you want to get url of the image
        //$src = wp_get_attachment_url( $id );
    }

error code: 523