I want to upload images in a unique folder. Then retrieve the path of this image saved on server like
http://example.com/wp-content/uploads/myimages/image1.jpg
Now I want to save this URL in a post having custom field as url.
I’ll be overwriting the posts on regular basis as well as replacing corresponding images, so I don’t want to keep the images related to previous posts (deleted posts) on my server (otherwise it would increase the memory on server). I want to delete all the images from myimages
folder. I don’t want to change the default path for uploads. Here’s my code for creating the post:
$new_post = array(
'post_title' => $phototitle,
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'post',
'post_category' => array(328)
);
$postid=wp_insert_post($new_post);
update_field('field_521c73f75a652',$photoid,$postid);
update_field('field_521c74a65a653',$phototitle,$postid);
update_field('field_521c74b25a654',$photourl,$postid);
update_field('field_521c74be5a655',$details,$postid);
update_field('field_521c77e72f9a6',$countinarr,$postid);
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$image = media_sideload_image($photourl, $postid, $phototitle);
$path = (string)$image;
$arr = (explode("'",$path));
$url = $arr[1];
update_field('field_521c758095f55',$url,$postid);
Please tell me how to change this upload path without making any change in wp-config.php
or media settings.
Here is simple function to create your own sub directory for every upload.
From my above code, I changed my images folder as
uploads_img
, you can change yours likewise.If you want more information, I wrote a tutorial for changing upload directories for every custom upload, take a look at my blog:
Notice: Haven’t tested my idea or code provided below.
*media_sideload_image* calls *wp_handle_upload* function which, suprisingly, handles file upload.
Upload dir is set via *wp_upload_dir* function. This function has a filter which can be used to modify it’s output (see http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/functions.php#L1607):
So hooking into that filter via:
The code pressume, that you have a hidden field in your code which set’s a check var with specific value agains you check in your filter. If that $_POST var is not present or has a different value, you return original array – thus you won’t break a standard image uploads.
And of course, you have to create all variables used in the filter, eg. $dir, $url etc. Check http://core.trac.wordpress.org/browser/tags/3.6/wp-includes/functions.php#L1525 to get and idea how WP does this.