Programmatically Creating Thumbnails in Wordpress Displays Image As Binary - php

I'm attempting to upload images into Wordpress programmatically. Everything is working except the last 2 lines where I attempt to generate image thumbnails and other intermediate sizes. The function, wp_generate_attachment_metadata(), appears to be correctly generating the new image sizes, but it then tries to display the resulting image as binary instead of returning the appropriate meta data array. Why is the binary (see image below) being echoed onto my screen? How do I suppress it?
$filetype = wp_check_filetype( basename( $image ), null );
$attachment = array(
'guid' => wp_upload_dir()['url'] . '/' . basename( $image ),
'post_mime_type' => $filetype['type'],
'post_content' => '',
'post_status' => 'inherit',
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $image ) )
);
$attach_id = wp_insert_attachment( $attachment, $image );
update_field('image', $attach_id, $post_id);
$attach_data = wp_generate_attachment_metadata( $attach_id, $image );
$response = wp_update_attachment_metadata( $attach_id, $attach_data );
This is a sampling of the binary echoed.

So it turns out that after the gibberish the function was displaying, was a short error message (failed to open stream: HTTP wrapper does
not support writeable connections). It turns out, the function "wp_generate_attachment_metadata" requires an absolute path to the image. Changing the $image variable to an absolute path (from a web path, http://website.com/path/to/image.png) fixed the issue.

Related

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.

how can i include image from front end of template using wordpress and php

In this piece of code, an empty file is getting stored in upload folder, but not a proper image file attached. I don't know why.
I'm also not getting the proper usage of wp_upload_bits, it writes a file in upload folder. I don't know how to change that to suite it for the uploading of an image.
I'm totally confused with the error in my code.
I know that there are multiple duplicate question related to it in stack overflow, but I'm not getting a proper result while using the solution described there. Please help me to find a solution.
My piece of code is as follows:
$upload = wp_upload_bits( $_FILES['file']['name'], null, file_get_contents( $_FILES['file']['tmp_name'] ) );
$wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $upload['url'] ,
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename( $upload['file'] )),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
update_post_meta( $post_id, '_thumbnail_id', $attach_id );
set_post_thumbnail( $post_id, $attach_id );
While using this code,attach file is getting stored in WordPress DB, but not in upload folder (media library).
I'm new to WordPress, so I am unable to find a solution for the reason of not storing a proper attached image file in upload folder.

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));

Image content printed on screen after inserting wordpress attachment programatically

I'm inserting attachment for a post like this programatically:
$wp_filetype = wp_check_filetype($gallery);
$attachment = array(
'guid' => '',
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($gallery)),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $gallery, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $gallery );
$update_data = wp_update_attachment_metadata( $attach_id, $attach_data );
Everything is working fine and attachment is added correctly but I get image code displayed on my page. :S
Something like this(I'm not going to post the whole code):
����JFIF``��;CREATOR: gd-jpeg v1.0 (using IJG JPEG v80), quality = 90 ��C ��C ����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�
Any ideas why this is happening?
You need to prepend the header Content-Type: image/jpeg before sending the contents of the image.
The browser can so interpret the file contents as jpeg and display it correctly.
With PHP: header("Content-Type: image/jpeg");

Categories