Download image and attach into post programmatically in WordPress 3


All we know, we can use wp_insert_post() to create content programmatically in WordPress. But, there more magic goodies bag in WordPress. We can download images and attach into post programmatically by using media_sideload_image(). There are several issue while using this function because lack of documentation about how to implement it.

The common error when using media_sideload_image() :
1. It generate blank page with errors.
2. Undefined function media_sideload_image()
3. Undefined function download_url()

To avoid all errors and use this into your plugin, just simply :

1
2
3
4
5
6
7
require_once(ABSPATH . ‘wp-admin/includes/media.php’);
require_once(ABSPATH . ‘wp-admin/includes/file.php’);
require_once(ABSPATH . ‘wp-admin/includes/image.php’);

$image_result = media_sideload_image($images_url, $post_id);

echo ‘<pre>’; var_dump($image_result);

Change “$images_url” with your images links also “$post_id “refer to your attached POST_ID. Easy right ? 🙂


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.