I have working code that uploads an image from the front end and sets it as a featured image and custom field photo for a custom post type but I am unable to figure out how to set the upload path.
Essentially if I have an employee I would like to use the custom field last_first to generate a folder path:
"wp-content/uploads/employee_mug/[last_first]/"
which would contain a photo of the employee. I require this as the folder structure is required for another page. The code is in my functions.php file but is simply in an if statement.
I've attempted to use move_uploaded_file with no success.
if (isset($_POST['last_first']) && is_user_logged_in()){
$my_post = array (
'post_type' => 'employee',
'post_status' => 'publish', // can also draft, private or publish
'post_title' => $_POST['last_first'],
);
$postID = wp_insert_post($my_post);
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$attach_id = media_handle_upload( $file, $postID );
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
update_field('date_of_birth', $_POST['dob'], $postID);
update_field('sex', $_POST['sex'], $postID);
die;}
I would like that when a file is attached the end result be:
"wp-content/uploads/employee_mug/[last_first]/1.jpg"
UPDATE 1.0
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$path = "./wp-content/uploads/mug_shots/";
$path .= $name;
if ( wp_mkdir_p( $path ) ) {
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
} else {
wp_mkdir_p( $path );
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
}
}
now checks to see if a folder was create and if not it will make one with the employee name but the move_uploaded file is not moving the photo into the generator folder. I simply need to find a way to make the file move to the generated folder at this point, Any help would be greatly appreciated!
UPDATE 2.0
the bellow code moves the file to wp-content/uploads/employee_mug/ but will not move it into the generated folder with the employee is name. I'm very close here I simply need the file moved into the employee is named folder at this point!
$name = $_POST['last_first'];
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
//for MKDIR FOR CREATION
$path = "./wp-content/uploads/employee_mug/";
$path .= $name;
//FOR MOVING UPLOADED IMAGE
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $name;
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
if ( wp_mkdir_p( $path ) ) {
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
} else {
wp_mkdir_p( $path );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
}
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
////////////////////////////////////////////////////////////////////////////////////////////
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
UPDATE 3.0 SOLVED ******
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $_POST['last_first'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
Related
I want to generate multiple image when passed image url through rest api.
and serialize '_wp_attachment_metadata' data in postmeta table like thisa:5:{s:5:"width";i:1920;s:6:"height";i:1200;s:4:"file";s:29:"2018/05/Haute-Panoramic-1.jpg";s:5:"sizes";a:8:{s:9:"thumbnail";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-300x188.jpg";s:5:"width";i:300;s:6:"height";i:188;s:9:"mime-type";s:10:"image/jpeg";}s:12:"medium_large";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-768x480.jpg";s:5:"width";i:768;s:6:"height";i:480;s:9:"mime-type";s:10:"image/jpeg";}s:5:"large";a:4:{s:4:"file";s:30:"Haute-Panoramic-1-1024x640.jpg";s:5:"width";i:1024;s:6:"height";i:640;s:9:"mime-type";s:10:"image/jpeg";}s:6:"slider";a:4:{s:4:"file";s:30:"Haute-Panoramic-1-1440x550.jpg";s:5:"width";i:1440;s:6:"height";i:550;s:9:"mime-type";s:10:"image/jpeg";}s:25:"real_estate_lite_property";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-400x300.jpg";s:5:"width";i:400;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:32:"real_estate_lite_property_slider";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-800x600.jpg";s:5:"width";i:800;s:6:"height";i:600;s:9:"mime-type";s:10:"image/jpeg";}s:27:"real_estate_lite_page_thumb";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-400x220.jpg";s:5:"width";i:400;s:6:"height";i:220;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
Here is the my code:-
$fetured_array=["https://media.architecturaldigest.com/photos/585811cfdcb583e908275f46/4:3/w_384/buildings-with-trees-001.jpg","https://media.architecturaldigest.com/photos/585811cfdcb583e908275f46/4:3/w_384/buildings-with-trees-001.jpg"]
$count_img=0;
foreach($feature_img as $url)
{
//$url = $feature_img;
$path = parse_url($url, PHP_URL_PATH);
$filename = mt_rand().basename($path);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($url);
$savefile = fopen($uploadfile, 'w');
chmod($uploadfile, 0777);
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'ID'=>$page_id,
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'post_parent'=>$new_post_id,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
if($count_img==0){
if ($attach_id) {
set_post_thumbnail( $new_post_id, $attach_id );
}
}
$newwidth = '250';
foreach ($attachment as $attached) {
$id = $attach_id;
$metadata = wp_get_attachment_metadata($id);
$metadata['width'] = $newwidth;
wp_update_attachment_metadata($id,$metadata);
}
array_push($fetured_array,$attach_id);
$count_img++;
}
$format_fetured_img=implode('|',$fetured_array);
update_post_meta($new_post_id, 'real_estate_property_images', $format_fetured_img);
Currently its working but only uploaded images into uploads/2018/5
folder with original size of the image. How can I upload image with
dynamic generate size as like when upload image in Media library by
wordpress admin
Please help me out to find the solution for the above.
Thanks in advance
Here is the solution.
First make sure you attached the image.php file just before the $fetured_array like this
require ( ABSPATH . 'wp-admin/includes/image.php' ); after that add thumbsize add_image_size( 'custom-size', 110, 100 );
Now after $attach_id = wp_insert_attachment( $attachment, $uploadfile ); add following two lines
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploadfile);
wp_update_attachment_metadata( $attach_id, $attach_data );
Now your code will work. This code is tested and its working fine.
I found the function to create it!! It will create all images automatically.
https://gist.github.com/m1r0/f22d5237ee93bcccb0d9
function crb_insert_attachment_from_url($url, $parent_post_id = null) {
if( !class_exists( 'WP_Http' ) )
include_once( ABSPATH . WPINC . '/class-http.php' );
$http = new WP_Http();
$response = $http->request( $url );
if( $response['response']['code'] != 200 ) {
return false;
}
$upload = wp_upload_bits( basename($url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name, null );
$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,
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
// Create the attachment
$attach_id = wp_insert_attachment( $post_info, $file_path, $parent_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_path );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id;
}
and for call this function, use it.
$xxx = crb_insert_attachment_from_url('http://ronaldoguedes.com.br/img/hello_word_2.png', null);
I am trying to upload various images from an URL to a given woocommerce product. The issue I am facing with my code is that, although I see that the images are being uploaded to the server, when I go to see my post I only see the last image uploaded to the gallery.
Here is my code:
function generateSecondImage($image_url, $post_id)
{
$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);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
$res3 = update_post_meta($post_id, '_product_image_gallery', $attach_id);
}
And here is how I call the function
for ($j=1; $j <$picCount ; $j++) {
generateSecondImage($pic[$j]->url, $post_id);
}
I am thinking that maybe, res3 is overwriting the gallery and showing only the last image posted, but if that is the case, how would I tell wordpress to include all of the images in the for loop?
Finally managed to solve it!
Here is my final code. My upload function goes like this:
function generateSecondImage($image_url, $post_id)
{
$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);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
echo "Attach ID is".$attach_id;
return $attach_id;
}
And then I had to create a comma-separated list of the IDs and add it to the add_post_meta
So my loop changed to this:
for ($j=1; $j <$picCount ; $j++) {
$attarray[] = generateSecondImage($pic[$j]->url, $post_id);
}
$commaList = implode(', ', $attarray);
$res3 = add_post_meta($post_id, '_product_image_gallery', $commaList);
Hope this helps anyone else looking for a solution.
I am trying to upload image through custom.php in wordpress when i print the
`$_FILES['uploadfiles'];`
its not showing any thing the same code i have used before one day in another wordpress site the code is working good over there on ec2 my current wordpress is on ec2 and have bitnami image i have checked all configuration like in php.ini file upload_tmp_dir=/opt/bitnami/php/tmp ,file_uploads=on,upload_max_filesize=40M.
i am not using any form i have just added upload field in one hook that display that field on one page.
I am using thesis theme.so any boday have any idea why this happening with this code on while one copy of same code work on another wordpress with guru theme.
Bellow is the code i am using to upload image.
<input type="file" name="uploadfiles[]" id="uploadfiles" size="35" class="uploadfiles" />
<?php
$uploadfiles = $_FILES['uploadfiles'];
print_r ($uploadfiles);
if (is_array($uploadfiles)) {
echo "1";
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
echo $attach_data;
echo $filedest;
wp_update_attachment_metadata( $attach_id, $attach_data );
//echo wp_get_attachment_url( $attach_id );
//exit();
$urlimage=wp_get_attachment_url( $attach_id );
$_SESSION["oldurl"]=$urlimage;
echo $_SESSION["oldurl"];
}
}
}
?>
I have the following code in my Wordpress. I need to add every uploaded image a counting number like, image_1, image_2, image_3 and so on..
The purpose of this is that every uploaded image attached to post, gets post ID name, and counting number in end to it.
It would be great if some one help me with this. Thanks!
<?php
add_filter('wp_handle_upload_prefilter', 'wpse_25894_handle_upload_prefilter');
add_filter('wp_handle_upload', 'wpse_25894_handle_upload');
function wpse_25894_handle_upload_prefilter( $file )
{
add_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $file;
}
function wpse_25894_handle_upload( $fileinfo )
{
remove_filter('upload_dir', 'wpse_25894_custom_upload_dir');
return $fileinfo;
}
function wpse_25894_custom_upload_dir($path)
{
/*
* Determines if uploading from inside a post/page/cpt - if not, default Upload folder is used
*/
$use_default_dir = ( isset($_REQUEST['post_id'] ) && $_REQUEST['post_id'] == 0 ) ? true : false;
if( !empty( $path['error'] ) || $use_default_dir )
return $path; //error or uploading not from a post/page/cpt
/*
* Save uploads in ID based folders
*
*/
$customdir = '/' . $_REQUEST['post_id'];
$path['path'] = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
$path['url'] = str_replace($path['subdir'], '', $path['url']);
$path['subdir'] = $customdir;
$path['path'] .= $customdir;
$path['url'] .= $customdir;
return $path;
}
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( 'image_make_intermediate_size', 'wpse_123240_rename_intermediates' );
function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Build our new image name
$postid = $_REQUEST['post_id'];
$random = rand(1,5);
$new_name = $dir . $postid . '_' . $random . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
?>
Now this code generates images named postid_randomnumber.jpg
I just need to add 20 images at maximum, so if I can have numbers from 1-20, that is also working fine with my purposes.
-- UPDATE --
I canged the last part of code to this, it is not maybe the cleanest solution, but it works:
function wpse_123240_rename_intermediates( $image )
{
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info['dirname'] . '/';
$ext = '.' . $info['extension'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
//$count = get_option( 'wpa59168_counter', 1 );
// Build our new image name
$postid = $_REQUEST['post_id'];
$increment = 1;
$new_name = $dir . $postid . '_1' . $ext;
while(is_file($new_name)) {
$increment++;
$new_name = $dir . $postid . '_' . $increment . $ext;
}
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
I have a script that allows me to upload an image to wordpress from the front end. I then need it to post the file to the post_meta. Right now it's working fine, BUT I end up with the Attachment ID and need the LINK to the file.
Here's the code that is handling this particular function.
if ($_FILES) {
foreach ($_FILES as $k => $v) {
if ($k != 'poster_has_paid' && $k != 'featured_image') {
if ($_FILES[$k]) {
wpo_poster_insert_attachment($k, $post_id, false, $k);
}
}
}
}
And here is the function wpo_poster_insert_attachment
function wpo_poster_insert_attachment($file_handler, $post_id, $setthumb = 'false', $post_meta = '') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) {
__return_false();
}
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload($file_handler, $post_id);
if ($setthumb) {
update_post_meta($post_id, '_thumbnail_id', $attach_id);
}
if (!$setthumb && $post_meta != '') {
update_post_meta($post_id, $post_meta, $attach_id);
}
return $attach_id;
Again, it's updating the field with the attach_id, and I'd like it to update the attach_url
PS I will give thanks when I have enough posts to do so. Thanks in advance.
Something like this should work
function wpo_poster_insert_attachment($file_handler,$post_id,$setthumb='false', $post_meta = '') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) {
update_post_meta($post_id,'_thumbnail_id',$attach_id);
// Get the attachment/thumbnail source, and add it to the post meta as well.
$src = wp_get_attachment_image_src($thumbnail_id, 'full');
update_post_meta($post_id,'_thumbnail_src', #$src[0]);
}
if(!$setthumb && $post_meta!=''){
update_post_meta($post_id, $post_meta, $attach_id);
}
return $attach_id;
}
But normally, since you already have the thumbnail_id stored in the post meta, you might want to pull the attachment source at run-time:
if($thumbnail_id = get_post_meta($post->ID, '_thumbnail_id', true)) {
$attachment_size = 'full';
$src = wp_get_attachment_image_src($thumbnail_id, $attachment_size);
if(!$src) {
$src = array('http://mysite.com/path/to/default-image.png', 640, 480);
}
echo '<img src="'.esc_url($src[0]).'" alt="" />';
}