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.
Related
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?
I have built a Wordpress plugin that polls an api, this api along with other data, returns URLs to images (the user polling the api owns these images). Moving the images from the api server to my server is time consuming but needs to be done as we want Wordpress to create multiple sizes of the images - thus we need to utilise it's upload functionality. Sometimes the data may return 500+ results each result could multiple images.
I am wanting to offset the image retrieval into a daily CRON job, however I cannot seem to get the cron to run, I have done the following in my code,
wp-config.php
define('DISABLE_WP_CRON', true);
I register a scheduled event in my plugin code like this,
wp_schedule_event( time(), 'daily', 'process_images_hourly' );
This theoretically should put this function (below) into a job list.
function process_images_hourly()
{
global $wpdb;
$results = $wpdb->get_results( "SELECT * FROM wp_autotrader_image_process WHERE process_status = 'Unprocessed';");
$processed_id = [];
foreach($results as $result) {
if(isset($result->image_url)) {
$upload_dir = wp_upload_dir();
$attachment_array = [];
if( !class_exists( 'WP_Http' ) ) {
include_once( ABSPATH . WPINC . '/class-http.php' );
}
$http = new WP_Http();
$file = file_get_contents($result->image_url);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$ext = $finfo->buffer($file);
if(strpos($ext, 'jpeg') || strpos($ext, 'jpg')) {
$type = '.jpg';
} elseif(strpos($ext, 'png')) {
$type = '.png';
} elseif(strpos($ext, 'gif')) {
$type = '.gif';
}
$response = $http->request( $result->image_url );
//die(print_r($image['secure']['href']));
if( $response['response']['code'] != 200 ) {
die(print_r($response['response']));
return false;
}
$upload = wp_upload_bits( basename($result->image_url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
die(print_r($upload));
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name . $type,
'post_mime_type' => $finfo->buffer($file),
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $post_info, $file_path );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
$attachment_array[] = $attach_id;
update_field( 'gallery', $attachment_array , $result->post_id );
$wpdb->delete( 'wp_autotrader_image_process', array( 'id' => $result->id ));
}
}
}
I then have cronjob on my server that does this,
*/15 * * * * curl https://Xxxxxx.xxxxxxxxx.com/wp-cron.php > /dev/null 2>&1 >/dev/null 2>&1
This runs the wp-cron file every fifteen minutes.
However I don't think my function is running, can anyone explain to why, or how set this up properly?
Thanks
add this code:
add_action( 'call_process_images_hourly', 'process_images_hourly' );
and update:
wp_schedule_event( time(), 'daily', 'call_process_images_hourly' );
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 have the following function to copy across a post as it's created on one site, to then move it over to a specific multisite blog:
function copy_across_to_multisite( $post_id ) {
// If this is just a revision, don't send the email.
if ( wp_is_post_revision( $post_id ) )
return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
if ($post_id && get_current_blog_id() == 1) {
$post = get_post($post_id, ARRAY_A); // get the original post
if ($post->post_status == 'trash' || $post->post_status == 'auto-draft') {
return $post_id;
}
$meta = get_post_meta($post_id);
$post_thumbnail_id = get_post_thumbnail_id($post_id);
$post_thumbnail = get_post($post_thumbnail_id, ARRAY_A);
$post['ID'] = ''; // empty id field, to tell wordpress that this will be a new post
$post_thumbnail['ID'] = '';
switch_to_blog(2); // switch to target blog
$inserted_post_id = wp_insert_post($post); // insert the post
$inserted_thumbnail = wp_insert_post($post_thumbnail);
foreach($meta as $key=>$value) {
update_post_meta($inserted_post_id,$key,$value[0]);
}
set_post_thumbnail($inserted_post_id, $inserted_thumbnail);
restore_current_blog(); // return to original blog
}
}
add_action( 'save_post', 'copy_across_to_multisite' );
This works great, but it doesn't bring across the featured image; I'm assuming because I need to also move the featured image into the upload folder for that multisite? The image does come across in the media library (albeit with no thumbnail and linking back to the other site - which I don't mind) but doesn't 'attach' onto the post and show up as a featured image.
Can anyone help out with this? Has anyone done anything similar? Thanks
Well, finally managed to (pretty much) cobble together a solution.
So in case anyone needs a similar function, it will take a little tweaking depending on your situation (changing the number in the switch_to_blog function as needed).
function copy_across_to_multisite( $post_id ) {
// If this is just a revision, don't send the email.
if ( wp_is_post_revision( $post_id ) )
return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
if ($post_id && get_current_blog_id() == 1) {
$post = get_post($post_id, ARRAY_A); // get the original post
if ($post->post_status['trash'] || $post['post_status'] == 'auto-draft') {
return $post_id;
}
$meta = get_post_meta($post_id);
$post_thumbnail_id = get_post_thumbnail_id($post_id);
$image_url = wp_get_attachment_image_src($post_thumbnail_id, 'full');
$image_url = $image_url[0];
$post['ID'] = ''; // empty id field, to tell wordpress that this will be a new post
switch_to_blog(2); // switch to target blog
$inserted_post_id = wp_insert_post($post); // insert the post
foreach($meta as $key=>$value) {
update_post_meta($inserted_post_id,$key,$value[0]);
}
// Add Featured Image to Post
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$filename = basename($image_url); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $inserted_post_id, $attach_id );
restore_current_blog(); // return to original blog
}
}
add_action( 'save_post', 'copy_across_to_multisite' );
I am using a new blog on WPMS (3.0.1, updating is unfortunately not an option at this point in time) to aggregate posts (and their featured image) from a few blogs on the same install, and I have to do it "programmatically" rather than through a pre-made plugin due to firewall restrictions. I've tried several ways of doing it, and feel like this method is most promising. Since my instance seems to be compounding complications, the few documented examples of how to use wp_insert_post and wp_insert_attachment aren't quite getting me all the way there. Here's what I've cooked up:
switch_to_blog(oldblognumber);
$zargs = array( 'numberposts' => 1, 'category_name' => 'featured');
$zlastpost = get_posts( $zargs );
foreach($zlastpost as $post) : setup_postdata($post);
$extrapost = array();
$extrapost['post_title'] = get_the_title();
$extrapost['post_content'] = get_the_content();
$extrapost['comment_status'] = 'closed';
$extrapost['post_status'] = 'publish';
$extrapost['post_date'] = get_the_date( $d = 'Y-m-d H:i:s');
$extrapost['post_category'] = array(catidnumber);
$upload_dir = wp_upload_dir();
$oldid = get_the_ID();
$image_url = wp_get_attachment_url(get_post_thumbnail_id($oldid));
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
switch_to_blog(newblognumber);
$file = $upload_dir['path'] . '/' . $filename; //removed the conditional cuz it was giving me trouble
file_put_contents($file, $image_data);
$post_id = wp_insert_post($extrapost);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit',
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
restore_current_blog();
wp_reset_postdata();
endforeach;
restore_current_blog();
The post insertion works just fine, and it pulls the image alright, but somewhere in there things are getting muddled and it spits out an absurd attachment url:
http://myblogs.com/newblog/wp-content/blogs.dir/newblognumber/files//internet/http/wp-content/blogs.dir/oldblognumber/files/year/month/filename.jpg
Likewise, in the loop where I ask for the_post_thumbnail, I get a broken image whose src is http://myblogs.com/newblog/files//internet/http/wp-content/blogs.dir/oldblognumber/files/year/month/filename-200x100.jpg
For what it's worth, since I'm using a pre set_post_thumbnail version of WP, I just manually define the function in my newblog's functions.php:
function set_post_thumbnail( $post, $thumbnail_id ) {
$post = get_post( $post );
$thumbnail_id = absint( $thumbnail_id );
if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
$thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' );
if ( ! empty( $thumbnail_html ) ) {
update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
return true;
}
}
return false;
}
I've tried fudging GUIDs and using regular expressions to force urls into submission among other things, but all to no avail.
I have also tried an alternate method of setting the post thumbnail of an inserted post, but this simply calls the original file in the oldblog's upload directory, which will not suffice, as I'd like to generate new image sizes for the newblog's Media Library, and I'd prefer to not go through and add them to each of the original oldblogs. Here's that attempt:
switch_to_blog(oldblognumber);
$zargs = array( 'numberposts' => 1, 'category_name' => 'featured');
$zlastpost = get_posts( $zargs );
foreach($zlastpost as $post) : setup_postdata($post);
$extrapost = array();
$extrapost['post_title'] = get_the_title();
$extrapost['post_content'] = get_the_content();
$extrapost['comment_status'] = 'closed';
$extrapost['post_status'] = 'publish';
$extrapost['post_date'] = get_the_date( $d = 'Y-m-d H:i:s');
$extrapost['post_category'] = array(catidnumber);
$oldid = get_the_ID();
$thumbo = get_the_post_thumbnail($oldid);
$filename = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
switch_to_blog(68);
$post_id = wp_insert_post($extrapost);
$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => _wp_relative_upload_path( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, false, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
update_post_meta( $post->ID, '_thumbnail_id', $attachment_id );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id);
restore_current_blog();
wp_reset_postdata();
endforeach;
restore_current_blog();
I've tried feeding a number of things to wp_insert_attachment's $filename parameter, but that doesn't seem to be my answer. Let me know if you've got any good ideas for me!
It turns out I was barking up the wrong (or at least a slightly different) tree by using wp_insert_attachment. media_sideload_image managed to pull attachments from other blogs on the same multisite install, copy them to the aggregating blog's uploads directory, and generate thumbnails, while wp_insert_attachment was doing what it was supposed to, which just happened to not be what I wanted. I realize that this is just a slight variation on other fairly well explained uses of similar functionality, but I figured I'd post my solution here in case anyone happens to have more success applying this particular combination of solutions.
I still get the sense that I'm not doing this in the most efficient way, but it's working for now:
function switch_and_insert($srcblog, $targetcat, $fromcat) {
switch_to_blog($srcblog);
$args = array( 'numberposts' => 1, 'category_name' => $fromcat);
$flastpost = get_posts( $args );
foreach($flastpost as $post) : setup_postdata($post);
$extrapost = array();
$extrapost['post_title'] = get_the_title($post);
$extrapost['post_content'] = get_the_post_thumbnail();
$extrapost['comment_status'] = 'closed';
$extrapost['post_status'] = 'publish';
$extrapost['post_date'] = get_the_date( $d = 'Y-m-d H:i:s');
$extrapost['post_category'] = array($targetcat);
$oldid = get_the_ID();
if ( has_post_thumbnail($oldid)) {
$filename = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
}
else $filename = $forchomper; // URL of backup image
switch_to_blog($aggregator_blog_id);
$post_id = wp_insert_post($extrapost);
$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => _wp_relative_upload_path( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
$sideloaded = media_sideload_image($filename, $post_id);
$attachments = get_children($post_id);
foreach ( $attachments as $attachment_id => $attachment );
set_post_thumbnail($post_id, $attachment_id);
restore_current_blog();
wp_reset_postdata();
endforeach;
restore_current_blog();
}
It might not be noteworthy, but nevertheless I will mention that using this method provided a very convenient opportunity to apply a placeholder image as a post thumbnail/featured image in the event that the originating post didn't have one, which is a different solution than the more widely suggested one that relies on a conditional within a theme used to display a placeholder, which doesn't actually assign it as a post's thumbnail. I realize that most of the time that is the better solution, but in my case these posts must have their own attached featured images, even if they are duplicates.
Here are a couple of the things that helped:
https://wordpress.stackexchange.com/a/19847/14351
http://old.nabble.com/Uploading-image-attachments-from-the-front-end-td26307647.html