Site icon Hip-Hop Website Design and Development

How to Insert images in WordPress using code

I am trying to create a plugin for auto posting. I was able to create new post and then get the attachment for the post. But images are not showing inside the post itself. but if I click on media library and select uploaded to this post, I can see image there.

Can somebody help in achieving the appropriate results.

$keywords = preg_replace('/ss+/', ' ',$_POST['keywords']);    
$keywords = explode("n",$_POST['keywords']);
$content = preg_replace('/ss+/', ' ',$_POST['content']);

$length = count($keywords);
for ($i = 0; $i < $length; $i++){
    $title = $keywords[$i];
    $contentfinal = str_replace("keyword",$title,$content);
    $post = array(
        'post_title'    => $title,
        'post_content'  => $contentfinal,
        'post_status'   => 'publish',
        'tags_input'    => $title
    ); 
    $post_id = wp_insert_post($post);
    echo "$post_id <br />";
    $newkeyword = strtolower($title);

    //upload image
        $filename = "http://www.domainname.com/wp-content/uploads/$newkeyword.jpg";
        echo $filename;
        $wp_filetype = wp_check_filetype(basename($filename), null );
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => preg_replace('/.[^.]+$/', '', basename($filename)),
            'post_content' => '',
            'post_status' => 'inherit'
        );
        $attach_id = wp_insert_attachment( $attachment, $filename, $post_id);
        require_once( ABSPATH . 'wp-admin/includes/image.php' );
        $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
        wp_update_attachment_metadata( $attach_id, $attach_data );  
        update_post_meta($post_id, '_thumbnail_id', $attachment_id);
        set_post_thumbnail( $post_id, $attach_id );
}