WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have played around with filters for uploading files. The closest I have gotten is to have the files uploaded to the directory, but after the file uploads, I get a series of errors: Undefined index: post_id I think the issue is as simple as not having access to the current post id. I have tried $wp_query->post->ID; and $post->ID and neither seem to work. These files would always be associated with a post.

The last iteration of the code I am using:

// filter for uploads
    function ml_media_upload_dir($upload) {

    $id = $_REQUEST['post_id'];
    $parent = get_post( $id )->post_parent;

        if (isset($_REQUEST['post_id'])) {
            $upload['path']    = "/foo/www/folder/blog/wp-content/uploads/" . $id;
            $upload['url']     = "http://foo.com/blog/wp-content/uploads/" . $id;
            $upload['basedir'] = "/foo/www/folder/blog/wp-content/uploads/" . $id;
            $upload['baseurl'] = "http://foo.com/blog/wp-content/uploads/" . $id;

            if (!file_exists("/foo/www/folder/blog/wp-content/uploads/" . $id)) {
                mkdir("/foo/www/folder/blog/wp-content/uploads/" . $id, 0777);

        return $upload;
    add_filter('upload_dir', 'ml_media_upload_dir');

I even tried adding another 'insert media' link with the post_action=1 param to test. (http://foo.com/blog/wp-admin/media-upload.php?post_id=571&TB_iframe=1&post_action=1&width=640&height=567)

How can I ensure that if there is a post_id, that the file gets loaded into the specific folder?

Any help..

cheers! Bo

share|improve this question
up vote 1 down vote accepted

Check if the argument is present, and if it isn't return the default value:

  return $upload;

// cast it to integer to avoid problems
$id = (int)$_REQUEST['post_id'];

share|improve this answer
sigh, in all the iterations, after a while I left that check out. It should've been there. thanks!! – roberthuttinger Apr 4 '12 at 19:21
Thanks, One Trick Pony! I was looking for a way to only show custom media fields added via attachment_fields_to_edit in WP 3.5 when they were attached to the post being viewed, and $_REQUEST['post_id'] was what I needed since $GOBALS['post'] is not set at that point. – goto10 Jun 13 '13 at 21:25

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.