I made a function which allows users to upload image to my wordpress site. Uploading works fine, but when I open a post with this uploaded image, the image doesn't show up. When I opened it in Firebug I noticed that image width and height is 0.
How can I upload image so it show up like I uploaded it with Media Library form.
This is my code:
if(isset($_FILES["image"])) {
if (!function_exists('wp_handle_upload')) require_once(ABSPATH . 'wp-admin/includes/file.php');
$uploadedfile = $_FILES['image'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($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'
);
$attach_id = wp_insert_attachment($attachment, $filename);
set_post_thumbnail($pageid, $attach_id);
}
}
Edit:
When I manually add width: 100% in Firebug, the image show up
I found a solution for this problem.
After the image was uploaded, meta data was not updated. So at the end of this function I added this:
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
This code updates the meta data for this image, therefore, Wordpress can find its dimensions.
Related
I am using the Board Game Geek API in order to pull in various data. One piece of data I want is the image.
For example, here is an API call for a particular board game:
https://boardgamegeek.com/xmlapi2/thing?id=169786&stats=1
When I get the response via my ajax call, I am able to grab the image url within the xml via:
var image_url = $(data).find("image")[0].textContent;
However: at that point I'm stumped. I want to upload the image that is located at that url, but I do not know how to upload the image via a form.
In wordpress: the only way I know how to upload images is if the image already exists on my computer. In that scenario, I have the following input:
<label for='board_game_image></label>
<input type="file" name="board_game_image" id="board_game_image" multiple="false"></input>
This input creates the "Choose Files" button to upload an image from your computer. Once the form is submitted, I use media_handle_upload to save the image within the uploads directory and create the relevant database records. Unfortunately: this process appears to not work when the image does not already exist on your computer, but instead exists somewhere on the internet (i.e. the image exists via the url).
Question: How can I upload an image via a wordpress front-end form when the image does not exist on my computer? Instead: all I have is the url of where the image exists on the internet.
You should include the image link on your form,
e.g.
var image_url = $(data).find("image")[0].textContent;
//assign the value to hidden input
$('#imgURL').val( image_url );
then add something like this on your form
<input type="hidden" id="imgURL" name="imageURL">
I'm not sure how you handle your form submission, but you can do something like below to process the image after submission.
First, save the image on uploads folder
$imgurl = $_REQUEST['imageURL']; // get the img url from the submitted data
$imginfo = pathinfo($imgurl); //get the url information
$filename = $imginfo['filename'].'.'.$imginfo['extension']; // extract the image filename
$updir = wp_upload_dir(); // get upload directory
$uploadedfile = $updir['path'] . '/' . $filename; // create upload image location & file name
$image= file_get_contents( $imgurl ); // get the image actual content
$saved = fopen($uploadedfile, 'w'); // open the image file
fwrite($saved, $image); // write image conent
fclose($saved); // close image
Your image is now uploaded and stored on wp-content uploads folder, and the exact location is at $uploadedfile
However, the image is still not added on media library as it doesn't have any database entry connected to that image,
Now simply use wp_insert_attachment function to link that image into a database and it will show on media library,
just check that documentation and you'll see an example of linking $uploadedfile file to media library, you can do something like,
$filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$img_id = wp_insert_attachment( $attachment, $uploadedfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $img_id, $uploadedfile );
wp_update_attachment_metadata( $img_id, $attach_data );
can you please check below 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;
I am scraping a site and putting data in my WP site.
There are lots of images in those posts.
I want that when importing that scraped data into my WP site,
I want to link images into my site directly from that external URL instead of downloading image to my server.
I am grammatically importing scraped data to my site.
Here is that part of adding image
// for image
$ins_q = "INSERT INTO wpxw_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, "
. "comment_status, ping_status,"
. "post_password, post_name, to_ping, pinged, post_modified,post_modified_gmt, post_content_filtered,post_parent,"
. "guid,menu_order,post_type,"
. "post_mime_type,comment_count) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$sth = $conn->prepare($ins_q);
if (!$sth->execute(array(
$post_author, $date, $date, "", sanitize_title_with_dashes($image_name), "", "inherit", "open", "closed", '',
str_replace(".", "-", $image_name), '', '', $date, $date, '', $post_id,
"http://photos2.zillowstatic.com/p_f/ISdc6hruhctopo0000000000.jpg"
, 0, "attachment", "image/jpeg", 0
))) {
echo "<h1>Error</h1>";
print_r($sth->errorInfo());
exit();
}
}
MY PROBLEM is that when adding external link to image, images do not show on my post. How can I show images from external resources?
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$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( $post_id, $attach_id );
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 a C# programmer - but trying to get into PHP.
I'm using a plugin to import Amazon products into a website.
My host however, blocks me from importing the images - which would normally be used as the featured image.
The code below sets the featured image when trying to import the images.
How can I change it to set the featured image, but to use the full URL to the original Amazon image link (I assume it's $image_url):
function set_featured_image( $post_id, $image_url ){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
$filename_ar = explode('.', $filename);
$filename = sanitize_file_name( $filename_ar[0] ).'.'.$filename_ar[1];
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 );
}
Or do I manually have to import the image and link to it locally?
Thanks for any help,
Mark
Is it an option to consider hot-linking the image? Keeps it from sapping bandwidth and storage on your site, and avoids the issue of needing to obtain and store a local copy of the image altogether.
I'm writing a Wordpress plugin to download remote images on my blog.
I made a function to upload a remote image locally, then returning its ID.
All seems OK except that
$attach_data = wp_generate_attachment_metadata( $attach_id, $local_file );
returns me an empty array - and it should not.
wp_generate_attachment_metadata is, among others, responsible of generating the thumbnails of the uploaded image. But I have no thumbnails created when I run my code.
I checked the values I send to the function and they seems correct : I have an ID and an absolute path to the uploaded file, as documented in the codex.
Still, I can't manage to have my code working :
$attach_data should not be empty...
Can anyone help ?
function upload_from_remote_url($url,$post_id){
$url = $this->validate_remote_media_url($url); //check file is not on local server
if (!$url) return false;
if ($existing_id = $this->media_already_exists($url)) return $existing_id; //url already has been downloaded
$upload_dir = wp_upload_dir();
$wp_mime_types = wp_get_mime_types();
//fetch image
$response = wp_remote_get( $url );
//get filename without extension
$filename = basename( $url ); //get filename & extension
$filename_strip = preg_replace('/\.[^.]*$/', '', $filename); //strip extension
//get extension from content type,
//because wp_upload_bits needs an extension and certain url don't have one.
$file_type = wp_remote_retrieve_header( $response, 'content-type' );
$extensions = array_search($file_type,$wp_mime_types);
$extensions_arr = explode('|',$extensions);
$extension = $extensions_arr[0];
$new_filename = $filename_strip.'.'.$extension; //full name
$new_filename = wp_unique_filename($upload_dir['path'], $new_filename); // be sure this name do not exist already
$uploaded = wp_upload_bits($new_filename, '', wp_remote_retrieve_body( $response ) );
if ($uploaded['error']) return false;
$local_file = $uploaded['file'];
$local_filename = basename($local_file);
$local_filetype = wp_check_filetype( $local_filename, null );
//Attachment options
$attachment = array(
'post_title'=> $local_filename,
'post_mime_type' => $local_filetype,
'post_status' => 'inherit'
);
// Add the image to your media library
$attach_id = wp_insert_attachment( $attachment, $local_file, $post_id );
if (!$attach_id) return false;
$attach_data = wp_generate_attachment_metadata( $attach_id, $local_file );
wp_update_attachment_metadata( $attach_id, $attach_data );
//save source link so we do not import several times the same media
update_post_meta($attach_id, 'grm_source', $url);
return $attach_id;
}
BTW, if any WP gourou had anything to say about this code... I'll be happy to read it, as the WP documentation about uploading files is a bit messy. I needed some specific stuff here, as being able to retrieve the file extension. I ended up to this but maybe you have some better ideas !
I've had a similar problem where mime type was missing. Since I use only one mime type, it was fixed by
'post_mime_type' => 'image/jpeg'
After that, it was still not updating the metadata, but forcing the update with "wp_update_attachment_metadata" solved the problem:
$attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
wp_update_attachment_metadata($attach_id, $attach_data);
This is, what finally fixed it for me:
apply_filters('wp_handle_upload', array(
'file' => $file_path,
'url' => $file_url,
'type' => $file_type),
'upload');
Explanation: I'm not quite sure why this fixed the error for me, but I assume that this either has something to do with plugins using the wp_handle_upload hook or that the filters add meta-data to the attachment, which otherwise would be missing in the wp_generate_attachment_metadata function.
Full function:
function add_to_media_lib($file_url, $file_path, $parent_post_id)
{
require_once(ABSPATH . 'wp-admin/includes/image.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
// Check the type of tile. We'll use this as the 'post_mime_type'.
$file_type = wp_check_filetype(basename($file_url), 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($file_url),
'post_mime_type' => $file_type['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($file_url)),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $parent_post_id
);
// Insert the attachment.
$attach_id = wp_insert_attachment($attachment, $file_url, $parent_post_id);
// apply filters (important in some environments)
apply_filters('wp_handle_upload', array('file' => $file_path, 'url' => $file_url, 'type' => $file_type), 'upload');
// Generate the metadata for the attachment, and update the database record.
if ($attach_data = wp_generate_attachment_metadata($attach_id, $file_path)) {
wp_update_attachment_metadata($attach_id, $attach_data);
} else {
echo '<div id="message" class="error"><h1>Failed to create PDF-thumbnail Meta-Data</h1><pre>' . print_r($attach_data) . '</pre></div>';
}
return $attach_id;
}
I know the topic is old but I was facing a similar issue and what worked for me was enabling the Crop thumbnail to exact dimensions (normally thumbnails are proportional) under Settings >> Media. I am using the media_handle_sideload() function by the way.