FPDF Class and WordPress PDF upload - php

I'm uisng FPDF for my PDF handling in my webshop. Whenever a user checks out I want to generate a PDF with all the data from the shopping cart and afterwards upload the PDF to the media library in WordPress.
I've tried a bunch of stuff now, but I haven't made anything yet that works. So far I can only save the PDF to a different folder by writing:
$pdf->Output($_SERVER['DOCUMENT_ROOT'].'/invoice/nameofinvoice.pdf', 'F');
My code looks like this:
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $pdf->Output('dimserPdf2014.pdf', 'F');
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
// die(var_dump($movefile));
$wp_filetype = $movefile['type'];
$filename = $movefile['file'];
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype,
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
// Id of attachment if needed
$attach_id = wp_insert_attachment( $attachment, $filename);
It does upload a file to the media library, but the file is empty, and if I uncomment the die > var_dump function I also get an array with simply nothing saying it's an empty file.
This is the script/class I'm using:
http://www.fpdf.org/
and the Output method accepts two parameters, filename and method of saving/downloading. As you can see here:
http://www.fpdf.org/en/doc/output.htm and I've tried every single parameter so far with no luck.
Any idea on why WordPress uploads an empty file and not my PDF?

I've been doing some work with mPDF, which is a (better documented & maintained imho) fork of FPDF. From what I can see in the documentation, the Output method doesn't return anything unless you pass the "S" dest.
Also, according to the Codex the file in wp_handle_upload is for working on one item in the $_FILES superglobal. You shouldn't need it in your case if you generate your PDF in the uploads directory.
Try this instead:
if ( ! function_exists ... ;
$wp_upload_dir = wp_upload_dir();
$uploadedfile = trailingslashit ( $wp_upload_dir['path'] ) . 'dimserPdf2014.pdf';
$pdf->Output($uploadedfile, 'F');
$attachment = array(
'guid' => trailingslashit ($wp_upload_dir['url']) . basename( $uploadedfile ),
'post_mime_type' => 'application/pdf',
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
// Id of attachment if needed
$attach_id = wp_insert_attachment( $attachment, $uploadedfile);

Related

Upload images to media gallery in Wordpress via wp_insert_attachment but avoid duplicates

I'm reading posts from a JSON file where the featured image for each post is an external URL. I'm creating a temp file and then uploading the image to Wordpress using wp_insert_attachment. Everything works fine if I only do this once. If I run my code twice, I'm getting duplicates of the images in the media gallery and I'm trying to prevent that. I want my code to say 'hey, if this image already exists and didn't change then don't upload it again'
What I'm currently doing: after I download the image and create a temp file, I sideload it into the uploads directory like this:
private function sideload() {
// Gives us access to the download_url() and wp_handle_sideload() functions.
require_once ABSPATH . 'wp-admin/includes/file.php';
// Download file to temp dir.
$temp_file = download_url( $this->url, 10 );
if ( is_wp_error( $temp_file ) ) {
return false;
}
$mime_type = mime_content_type( $temp_file );
if ( ! $this->is_supported_image_type( $mime_type ) ) {
return false;
}
// An array similar to that of a PHP `$_FILES` POST array
$file = array(
'name' => $this->get_filename( $mime_type ),
'type' => $mime_type,
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize( $temp_file ),
);
$overrides = array(
'test_form' => false, //there are no form fields so false
'test_size' => true, //false allows empty files
'test_upload' => true, //properly uploaded files will pass
);
// Move the temporary file into the uploads directory.
$file_attributes = wp_handle_sideload( $file, $overrides );
if ( $this->did_a_sideloading_error_occur( $file_attributes ) ) {
return false;
}
return $file_attributes;
}
then, I insert the attachment like this:
private function insert_attachment( $file_path, $mime_type ) {
// Get the path to the uploads directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment_data = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $file_path ),
'post_mime_type' => $mime_type,
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_path ) ),
'post_content' => '',
'post_status' => 'inherit',
);
$attachment_id = wp_insert_attachment( $attachment_data, $file_path );
if ( ! $attachment_id ) {
return;
}
$this->attachment_id = $attachment_id;
}
Could you help me realize what I'm doing wrong in order to avoid duplicates of my images? How do I know if an image has changed before I upload it to media gallery?
Thanks!

How to I upload to wordpress media library

I have a custom php form that upload images to a folder on my website. Currently that folder is outside the wp-content folder.
I want the content of the folder to be automatically uploaded to Google drive. There are plenty of plugins or a zapier solution to do that if the folder is in the wp media folder.
My question is...Can I just upload the images directly to the wp media folder or do I need to use a special wp method/function/api call.
Yes you can upload media directly to the media library. Given your situation media_handle_upload() is probably the most logical way. Can read its documentation here: https://developer.wordpress.org/reference/functions/media_handle_upload/
Take a look at this https://wordpress.stackexchange.com/a/60807/180725
Once you upload the media (to where you want, ftp, dropbox, s3 etc) you will need to register it with Wordpress.
$file_name = 'Some Name';
$file_path = '/path/to/uploads/2012/08/04/newfile.jpg';
$file_url = 'http://url/to/uploads/2012/08/04/newfile.jpg';
$wp_filetype = wp_check_filetype($file, null);
$attachment = array(
'guid' => $file_url,
'post_mime_type' => $wp_filetype['type'],
'post_title' => $file_name,
'post_status' => 'inherit',
'post_date' => date('Y-m-d H:i:s')
);
$attachment_id = wp_insert_attachment($attachment, $file_path);
$attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
wp_update_attachment_metadata($attachment_id, $attachment_data);
If you are looking for a solution to upload files to wordpress Mediathek / Library from an external Source/URL, I recommend the following code:
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path']))
$file = $upload_dir['path'] . '/' . $filename;
else
$file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);
$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 );
Original post here: https://wordpress.stackexchange.com/a/169598

Wordpress Generate Attachment Metadata not working

i am trying to insert posts automatically to wordpress. Posts i posted is very well but somehow i can't generate metadatas for thumbnails.
Here is my code for metadatas
$filetype = wp_check_filetype( basename( $thumb ), null );
$bol = explode('/', $thumb);
$fileur = $bol[count($bol)-1];
$wp_upload_dir = wp_upload_dir();
$tits = $wp_upload_dir['path'].'/'.basename($thumb);
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $thumb ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $thumb ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id=wp_insert_attachment($attachment, $tits, $post_id);
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $tits );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail($post_id,$attachment_id);
I read all the connected questions on community but it doesnt helped my issue. Best regards
According to this WP wiki page: wp_insert_attachment you must use unchanged file path from upload dir for these functions: wp_insert_attachment, wp_generate_attachment_metadata
In your codebase, I see that you're doing something wrong with your $thumb like extracting its basename and building a new path that lives in $tits. I am 99% sure that the problem is of wrong file path.

Attach multiple files (jpeg, m4v, 3gp) to a wordpress post

Here is the function that I used to insert attachments to a post.
function insert_entries($filename, $parent_post_id){
$wp_upload_dir = wp_upload_dir();
$filetype = wp_check_filetype( basename( $filename ), null );
$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'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
The issue with this is that, When I am trying to insert any files after inserting a 3gp or m4v file, its not getting inserted. Any insight to solve this is welcome..
Thanks in advance..
Atlast got it fixed.
The reason for the issue was when we try to insert any audio or video files the wordpress tries extract its metadata which was causing for a fatal error.
The simple fix for this is to go to includes/image.php and remove all references to wp_read_video_metadata()

import bulk images to wordpress

I am migrating a very big website to wordpress.
I have about 35,000 images that I need to migrate to the wordpress environment from a custom cms made in native php.
I have uploaded the files via ftp to the wp-content directory but the wordpress media does not seem to recognize it, since it's missing the meta data in the mysql database.
I found the "add from server" plugin, but that plugin is limited to manually selecting images but when I select many images at once, it crashes.
Are there any other solution out there?
Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator. Then use wp_insert_attachment to add them to the WordPress database.
Note: I was not able to test this, but this is the general concept.
// Get WP uploads dir
$wp_upload_dir = wp_upload_dir();
// Init recursive Obj
$di = new RecursiveDirectoryIterator($wp_upload_dir['path']);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
// get filetype for attachment meta
$filetype = wp_check_filetype( $file->getPathname(), null );
// attachment meta
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . $filename,
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename );
}
When I was migrating a site with more than 55345 articles with images, I wrote some pure PHP scripts that perform migration, and then inserted images as follows (based on the explanation given by jackreichert):
$uploads = wp_upload_dir();
$save_path = $uploads['basedir'].'/importecms/'.$new_filename;
$attach_id = wp_insert_attachment( $artdata, $save_path, $post_id );
if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
wp_update_attachment_metadata($attach_id, $attach_data);
}
$rows_affected = $wpdb->insert($wpdb->prefix.'postmeta', array('post_id' => $post_id, 'meta_key' => '_thumbnail_id', 'meta_value' => $attach_id));

Categories