
I have a frontend form that allows images to be added within a repeater field.
To keep things organized, I’d like the images to save in a custom upload location — uploads/post/[post_id].
The code works when posting from the backend — the images end up in uploads/post/[post_id]. When posting from the frontend the images are placed in uploads/post.
How do I hook into the save process to make post_id available to acf/upload_prefilter? Or is there another approach that I should be taking?
Also note that in production the form will be available to subscribers on the frontend who don’t have the upload_files capability, so the image(s) won’t actually be uploaded until the form is submitted.
new-post.php
acf_form_head();
get_header();
while ( have_posts() ) : the_post();
acf_form(array(
'post_id' => 'new_post',
'new_post' => array(
'post_type' => 'post',
'post_status' => 'publish'
),
'submit_value' => 'Create New Post'
));
endwhile;
get_footer();
functions.php
add_filter('acf/upload_prefilter', 'my_upload_prefilter');
function my_upload_prefilter($errors) {
add_filter('upload_dir', 'my_custom_post_upload_dir');
return $errors;
}
function my_custom_post_upload_dir($uploads) {
$post_id = ( isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : '' );
$subdir = $post_id;
$uploads['subdir'] = $subdir;
$uploads['url'] = $uploads['baseurl'] . '/post/' . $subdir;
$uploads['path'] = $uploads['basedir'] . '/post/' . $subdir;
return $uploads;
}