1
    $filePath = wp_get_attachment_url( $id );
$tempfilename = explode("/", $filePath);
$temppdffile = end($tempfilename);
$cuurentPath = plugin_dir_path( __FILE__ ).$temppdffile;
$im = new Imagick();
$im->setResolution(300, 300);
$im->readImage( $cuurentPath.'[0]'); 
$im->setImageFormat('jpg');

I have above code.. i have successsfully generated image.. $im But i have to save image to.. media in wordpress as a featured image ? Any idea.. tried every thing

2

I'm not too familiar with Imagick, but if you can get a URL for the image you've created with it, then the rest is fairly straightforward using WordPress's media_sideload_image() function. Here's a basic example that would work from wp-admin area(like settings page). Note that it looks like you'd use your $id variable in place of my $post_id:

// load image from URL into media library, set a post as its parent, and return new attachment's id
$attachment_id = media_sideload_image( $image_url, $post_id, $img_title, 'id'); 
if( !is_wp_error( $attachment_id ) ) { // if no error returned...
    // ...Set above loaded image as the featured image of the current post
    set_post_thumbnail($post_id, $attachment_id);
}

Note that Codex says third param of media_sideload_image sets description of the image, but it sets image title. Also, they just added the fourth parameter for returning the attachment id in 4.8, so hopefully you're up to date.

More Info:

Also note that if you're implementing this in the front end you'll need to include the following three files in your script so that media_sideload_image can handle the uploading, etc it does for us:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.