Hy, i have this function:
function process_pdf( $file ) {
if( $file['type'] === 'application/pdf' ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
$filename = $file[ 'name' ];
$filename_wo_extension = basename( $filename, ".pdf" );
$im = new Imagick();
$im->setResolution(300, 300);
$im->setBackgroundColor('white');
$im->readimage( $file[ 'tmp_name' ] );
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$pages = $im->getNumberImages();
$attachments_array = array();
// iterate over pages of the pdf file
for($p = 1; $p <= $pages; $p++){
$im->setIteratorIndex( $p - 1 );
$im->setImageFormat('jpeg');
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$page_title = get_the_title($post_id);
$filename_neu = $page_title .'_pagina_'. $p .'.jpg';
// upload new image to wordpress
// https://codex.wordpress.org/Function_Reference/wp_insert_attachment
$upload_file = wp_upload_bits($filename_neu, null, $im);
if (!$upload_file['error']) {
$attachment = array(
'post_mime_type' => 'image/jpeg',
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename_neu),
'post_content' => '',
'post_parent' => $post_id,
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );
if (!is_wp_error( $attachment_id )) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
$attachments_array[] = $attachment_id;
}
}
}
// add new images to a gallery (advanced custom fields plugin)
// http://www.advancedcustomfields.com/resources/update_field/
//update_field( 'field_62a736b215b2f', $attachments_array, $post_id );
$im->destroy();
}
}
return $file;
}
add_filter('wp_handle_upload_prefilter', 'process_pdf' );
when i upload PDF file on wordpress all page is converted to JPG and upload in site.
Function work and do what i need, but problem appear when i upload THIS File:
https://easyupload.io/o6hsk3
for understand where is the problem:
i try to compare this file with another;
i upload a big pdf file with more resolution, page.
All work good, but this pdf file not work:(
have any ideea why?
Related
I am trying to add WooCommerce Product Gallery using Gravity forms multiple file upload but product gallery should not be added
add_action( 'gform_after_submission_3', 'set_post_content', 10, 2 );
function set_post_content( $entry, $form ) {
if (!function_exists('wp_generate_attachment_metadata')) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
}
$uploaded_files = json_decode(rgpost("gform_uploaded_files"));
foreach($uploaded_files->input_76 as $key => $data){
if (isset($_FILES[$data])) {
$file_url = $data->input_76; //great but what is its url?
$upload_dir = wp_upload_dir(); //where do you want to put it?
$file_data = file_get_contents($file_url); //show me what you're made of
$filename = basename($file_url); //so cute but what's its name?
if (wp_mkdir_p($upload_dir['path'])) //can we put it there?
$file = $upload_dir['path'] . '/' . $filename; //yes great
else //or no, okay fine let's try somewhere else
$file = $upload_dir['basedir'] . '/' . $filename; //get the whole location
file_put_contents($file, $file_data); // tada home at last
//$wp_filetype = wp_check_filetype($filename, array('pdf' => 'application/pdf','pdf' => 'application/x-pdf') ); //is it the right type of of file?
$attachment = array(//set up the attachment
//'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file, $entry['post_id']); //insert attachment
$attach_data = wp_generate_attachment_metadata($attach_id, $file); //asign the meta
wp_update_attachment_metadata($attach_id, $attach_data); //update the post
update_post_meta($entry['post_id'], '_product_image_gallery', $attach_id);
}
}
}
I have a site with a frontend form where users can add new post. The form has some basic post details and an featured image field. The form also has a few more image fields, which are controlled by acf.
Now the issue is when i use images like png everything works fine. But when i use images like jpg, it gives a internal server error. In acf i have added the accepted file formats as "jpg,png,jpeg". But i am not sure how to add file formats for the featured image.
Here is the code i am using. Here the first image will always be the featured image.
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
if($count==1){
$featured_image_id = upload_user_file( $file );
}else{
$item_image[] = upload_user_file( $file );
}
}
$count++;
}
And here is the upload_user_file function
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
Ok i solved it. For some reason the allowed file types in acf didn't work for me. So i just removed the types (ie allow all file types) and everything came back to life. I know this might not be suitable for everyone, but i guess this points you in the right direction of where the issue might be.
I am trying to upload an image through PHP script as mentioned below. I am taking image from the URL;
I have taken reference from this post Actually in my case I want to upload it to WordPress upload folder where post images get upload and you know WordPress creates folder on run-time inside 'wp-content/uploads/' and it uploads image there. So path ($save_path) is not decided on run time.
$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);
I am trying to use WordPress function "media_handle_upload" to upload image instead of "file_put_contents" but I am not getting how I pass file object to this function once i get the file contents ($contents=file_get_contents($url);). Kindly assist.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['post_id'] );
100% working this code:
include_once( ABSPATH . 'wp-admin/includes/image.php' );
$imageurl = '<IMAGE URL>';
$imagetype = end(explode('/', getimagesize($imageurl)['mime']));
$uniq_name = date('dmY').''.(int) microtime(true);
$filename = $uniq_name.'.'.$imagetype;
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($imageurl);
$savefile = fopen($uploadfile, 'w');
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
echo $attach_id;
Here is complete example :
// $filename should be the path to a file in the upload directory.
$filename = '/path/to/uploads/2013/03/filename.jpg';
// The ID of the post this attachment is for.
$parent_post_id = 37;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
You can check wp_insert_attachment() for more info
I'm working on a plugin which creates jpgs from every page of an uploaded pdf file.
I use the wp_handle_upload action and check if the mime type is pdf.
After that, I use Imagick to get the page count and create a new jpg from every page. Then the file gets uploaded.
I think Wordpress doesn't support ImageMagick from scratch so I installed the ImageMagick Engine Plugin.
When I now upload a file in Wordpress I just get an error. I don't know what exactly doesn't work.
Any idea about what is going wrong?
Thanks, Oliver
function process_pdf($results) {
if( $results['type'] === 'application/pdf' ) {
$filename = $results[ 'file' ];
$filename_wo_extension = basename( $filename );
$url = $results[ 'url' ];
$im = new Imagick();
$im->setResolution(300, 300);
$pages = $im->getNumberImages();
for($p = 0; $p < $pages; $p++){
// http://stackoverflow.com/questions/467793/how-do-i-convert-a-pdf-document-to-a-preview-image-in-php
// http://stackoverflow.com/questions/1143841/count-the-number-of-pages-in-a-pdf-in-only-php
$im->readImage( $url.'['.p.']');
$im->setImageFormat('jpg');
$filename_neu = $filename_wo_extension .'_'. $p .'.jpg';
// https://codex.wordpress.org/Function_Reference/wp_insert_attachment
$upload_file = wp_upload_bits($filename_neu, null, $im);
if (!$upload_file['error']) {
$attachment = array(
'post_mime_type' => 'image/jpeg',
'post_title' => preg_replace('/\.[^.]+$/', '', $filename_neu),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
}
}
}
add_action('wp_handle_upload', 'process_pdf');
Here is the code for achieving this.
The pdf file has to be uploaded to a post, otherwise there is no $post_id.
The only thing now is, that when clicking on save, the custom field (gallery) gets overwritten. When the post is not saved after uploading the pdf, the images are in the gallery.
function process_pdf( $file ) {
if( $file['type'] === 'application/pdf' ) {
// Get the parent post ID, if there is one
if( isset($_REQUEST['post_id']) ) {
$post_id = $_REQUEST['post_id'];
$filename = $file[ 'name' ];
$filename_wo_extension = basename( $filename, ".pdf" );
$im = new Imagick();
$im->setResolution(300, 300);
$im->readimage( $file[ 'tmp_name' ] );
$pages = $im->getNumberImages();
$attachments_array = array();
// iterate over pages of the pdf file
for($p = 1; $p <= $pages; $p++){
$im->setIteratorIndex( $p - 1 );
$im->setImageFormat('jpeg');
$filename_neu = $filename_wo_extension .'_'. $p .'.jpg';
// upload new image to wordpress
// https://codex.wordpress.org/Function_Reference/wp_insert_attachment
$upload_file = wp_upload_bits($filename_neu, null, $im);
if (!$upload_file['error']) {
$attachment = array(
'post_mime_type' => 'image/jpeg',
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename_neu),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'] );
if (!is_wp_error( $attachment_id )) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
$attachments_array[] = $attachment_id;
}
}
}
// add new images to a gallery (advanced custom fields plugin)
// http://www.advancedcustomfields.com/resources/update_field/
update_field( 'field_55b0a473da995', $attachments_array, $post_id );
$im->destroy();
}
}
return $file;
}
add_filter('wp_handle_upload_prefilter', 'process_pdf' );
I know this is an old thread, but anyway, I would like to say that there is a very fine WordPress plugin that deals with PDF files, converting the first page into an image, using either ImageMagick or IMagik (it let's you chose what you have installed on your site).
As the source code if freely available, I guess it might be of some help for whoever might be researching on this matter:
PDF IMAGE GENERATOR
https://wordpress.org/plugins/pdf-image-generator/
I'm trying to create plugin importing posts to WordPress. Imported articles (XML) contain "image-name" attribute and this image is already uploaded to the server.
I would like to, however, make WordPress do its "magic" and import the image to the system (create thumbnails, attach it to the post, place it under the wp-uploads directory scheme)... I found function media_handle_upload($file_id, $post_id, $post_data, $overrides) but it requires array $_FILES to be filled with actual upload (and I'm not uploading file - it is already placed on the server) so it's not very useful
Do you have any hint how to proceed?
Thanks
Check the following script to get the idea. (It does work.)
$title = 'Title for the image';
$post_id = YOUR_POST_ID_HERE; // get it from return value of wp_insert_post
$image = $this->cache_image($YOUR_IMAGE_URL);
if($image) {
$attachment = array(
'guid' => $image['full_path'],
'post_type' => 'attachment',
'post_title' => $title,
'post_content' => '',
'post_parent' => $post_id,
'post_status' => 'publish',
'post_mime_type' => $image['type'],
'post_author' => 1
);
// Attach the image to post
$attach_id = wp_insert_attachment( $attachment, $image['full_path'], $post_id );
// update metadata
if ( !is_wp_error($attach_id) )
{
/** Admin Image API for metadata updating */
require_once(ABSPATH . '/wp-admin/includes/image.php');
wp_update_attachment_metadata
( $attach_id, wp_generate_attachment_metadata
( $attach_id, $image['full_path'] ) );
}
}
function cache_image($url) {
$contents = #file_get_contents($url);
$filename = basename($url);
$dir = wp_upload_dir();
$cache_path = $dir['path'];
$cache_url = $dir['url'];
$image['path'] = $cache_path;
$image['url'] = $cache_url;
$new_filename = wp_unique_filename( $cache_path, $filename );
if(is_writable($cache_path) && $contents)
{
file_put_contents($cache_path . '/' . $new_filename, $contents);
$image['type'] = $this->mime_type($cache_path . '/' . $new_filename); //where is function mime_type() ???
$image['filename'] = $new_filename;
$image['full_path'] = $cache_path . '/' . $new_filename;
$image['full_url'] = $cache_url . '/' . $new_filename;
return $image;
}
return false;
}