1

How to I get the current post id while in admin? I want to use a custom upload dir based on the post ID but i cant seem to retreive it?

add_filter( 'wp_handle_upload_prefilter', 'do_pre_upload' );

function do_pre_upload( $file ) {
add_filter( 'upload_dir', 'do_custom_upload_dir' );
        return $file;
}

function do_custom_upload_dir( $param ) {

    global $post; 
    $id = 344;  // HOW DO IT GET THE CURRENT POST ID
    //$id = $post->ID;  // DOESNT WORK DOESNT GET A VALUE?????


    $parent = get_post( $id )->post_parent;
    if( "client_gallery" == get_post_type( $id ) || "client_gallery" == get_post_type( $parent ) ) {
        $mydir         = '/client_galleryy/'.$post->ID.'';
        $param['path'] = $param['basedir'] . $mydir;
        $param['url']  = $param['baseurl'] . $mydir;
    }



   return $param;


}

UPDATE

Here is my full code for my plugin which creates my custom post type, creates a meta box using the meta box plugin and now the code for setting the upload dir for my custom post type / post id. I must have the code for the upload dir in the wrong spot as its not determining that im in my custom post type and that it should be creating the new upload dir for the post?

**
 * Plugin Name: My Plugin Name
 * Plugin URI: domain.com
 * Description: my description
 * Version: 1.0.0
 * Author: My Name
 * Author URI: domain.com
 * License: GPL2
 */





// START CREATE CUSTOM POST TYPE
add_action( 'init', 'create_post_type' );
function create_post_type() {
    register_post_type( 'client_gallery',
        array(
            'labels' => array(
                'name' => __( 'Galleries' ),
                'singular_name' => __( 'Gallery' )
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array( 'title' ),
        )
    );




}
// END CREATE CUSTOM POST TYPE


// START CREATE META BOX
add_filter( 'rwmb_meta_boxes', 'xyz_gallery_meta_boxes' );
function xyz_gallery_meta_boxes( $meta_boxes ) {




    $meta_boxes[] = array(
        'title'      => __( 'Gallery Images', 'textdomain' ),
        'post_types' => 'client_gallery',
        'fields'     => array(
    array(
        'name'             => esc_html__( 'Image', 'textdomain' ),
        'id'               => "clientImage",
        'type'             => 'image_advanced',
    ),
        ),
    );


    return $meta_boxes;
}
// END CREATE META BOX






/**
 * Modify Upload Directory Based on Post Type
 *
 * @param Array $dir
 *
 * @return Array $dir
 */
function wpse_247197( $dir ) {
    $request_arr    = array( 'upload-attachment', 'editpost', 'editedtag' );
    $request        = array_change_key_case( $_REQUEST, CASE_LOWER );   // WordPress uses post_id and post_ID
    $type           = null;

    // Are we where we want to be?
    if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {
        return $dir;
    }

    if( isset( $request['post_id'] ) ) {            // Get Post ID
        $id = $request['post_id'];

        if( isset( $request['post_type'] ) ) {      // Get the post type if it was passed
            $type = $request['post_type'];
        } else {                                    // If not passed, get post type by ID
            $type = get_post_type( $id );
        }
    } else {                                        // If we can't get a post ID return default directory
        return $dir;
    }

    if( isset( $type, $id ) && in_array( $type, $post_type_arr ) ) {

        // Here we can test our type and change the directory name etc. if we really wanted to
        if( 'client_gallery' != $type ) {
            return $dir;
        }

        $uploads     = apply_filters( "{$type}_upload_directory", "{$type}/{$id}" );        // Set our uploads URL for this type
        $dir['url']  = path_join( $dir['baseurl'], $uploads );                              // Apply the URL to the directory array
        $dir['path'] = path_join( $dir['basedir'], $uploads );                              // Apply the Path to the directory array
    }

    return $dir;
}
add_filter( 'upload_dir', 'wpse_247197' );
// END Modify Upload Directory Based on Post Type
4
  • 3
    wp_handle_upload_prefilter is fired too early that post data is not set yet. There are plenty workarounds, e.g saving some hint in postmeta to use later to move the file to the post ID named category..
    – Ismail
    Nov 23, 2016 at 17:56
  • can you provide an example to work around this?
    – knmsuser
    Nov 23, 2016 at 18:01
  • How do you upload these files? You can add a param to URL for post_id then set the directory from that GET param..
    – Ismail
    Nov 23, 2016 at 18:04
  • I have a custom post type called client_gallery . IF i "Add Media" from within this post type I want it to upload to /wp-content/uploads/client_gallery/POSTID/filename.jpg
    – knmsuser
    Nov 23, 2016 at 18:16

3 Answers 3

2

Based on your comments, it sounds like you just want a custom directory for your post type called client_gallery which is fairly straight-forward actually. The below just uses the upload_dir hook to achieve this:

/**
 * Modify Upload Directory Based on Post Type
 *
 * @param Array $dir
 *
 * @return Array $dir
 */
function wpse_247197( $dir ) {
    $request_arr    = array( 'upload-attachment', 'editpost', 'editedtag' );
    $request        = array_change_key_case( $_REQUEST, CASE_LOWER );   // WordPress uses post_id and post_ID
    $type           = null;

    // Are we where we want to be?
    if( ! ( isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $request_arr ) ) ) {
        return $dir;
    }

    if( isset( $request['post_id'] ) ) {            // Get Post ID
        $id = $request['post_id'];

        if( isset( $request['post_type'] ) ) {      // Get the post type if it was passed
            $type = $request['post_type'];
        } else {                                    // If not passed, get post type by ID
            $type = get_post_type( $id );
        }
    } else {                                        // If we can't get a post ID return default directory
        return $dir;
    }

    if( isset( $type, $id ) && ! empty( $type ) && ! empty( $id ) ) {

        // Here we can test our type and change the directory name etc. if we really wanted to
        if( 'product' != $type ) {
            return $dir;
        }

        $uploads     = apply_filters( "{$type}_upload_directory", "{$type}/{$id}" );        // Set our uploads URL for this type
        $dir['url']  = path_join( $dir['baseurl'], $uploads );                              // Apply the URL to the directory array
        $dir['path'] = path_join( $dir['basedir'], $uploads );                              // Apply the Path to the directory array

        error_log( print_r( $dir, 1 ) );
    }

    return $dir;
}
add_filter( 'upload_dir', 'wpse_247197' );

I've heavily commented the above code so should you have any questions regarding it you may ask in the comments. The idea is that whenever a user uploads to the post type itself it will get uploaded directly to the folder. This is not the case with assigning a pre-uploaded attachment media - moving the files once they've already been uploaded and the URLs have been set would be extremely troublesome.

7
  • This didnt work as i dont think im getting the post_id or post types. Where should this code go? I have tried it in my plugin php file at the end of the file and i've tried it in my functions.php file for my theme?
    – knmsuser
    Nov 24, 2016 at 13:15
  • Ive added an update to the original post which now includes my full plugin php file with your code in it. Its still not creating the dir for the custom post type/post id so i'm thinking I do not have this in the correct spot?
    – knmsuser
    Nov 24, 2016 at 14:32
  • Was wondering if you could review my full code in the "update" posted. i'm still having trouble getting this to work? Am I putting your code in the right spot? It stull doesnt appear to be getting the post id and or post type?
    – knmsuser
    Nov 28, 2016 at 14:51
  • @knmsuser I've updated my code - that should work, the only thing I can think of is that whatever metabox plugin you're using is the issue.
    – Howdy_McGee
    Nov 28, 2016 at 15:18
  • Thank you for all your help so far. I'm still having dificullty and I now know its related to my custom post type. I have commented out your section where it tests the post type so it should create a dir/id for post if im in post (and it does), page if im in page (and it does) BUT NOT for my custom post type? thoughts?
    – knmsuser
    Dec 4, 2016 at 21:51
1

$post is an object, you can get the post id like this

  $id = $post->ID;
1
  • this doesnt seem to return a value. id is blank if i use this?
    – knmsuser
    Nov 23, 2016 at 17:59
0

You can get POST ID by $_REQUEST .

add_action('init',function(){
   global $post;

   if($post){
       session_start();
       $_SESSION['p_id'] = $post->ID;
   }

});

add_filter( 'wp_handle_upload_prefilter', 'do_pre_upload' );

function do_pre_upload( $file ) {

        add_filter( 'upload_dir', 'do_custom_upload_dir' );
        return $file;
}

function do_custom_upload_dir( $param ) {

    // Get the current post_id
    $id = ( isset( $_SESSION['p_id'] ) ? $_SESSION['p_id'] : '' );

    unset($_SESSION['p_id']);

    $parent = get_post( $id )->post_parent;
    if( "client_gallery" == get_post_type( $id ) || "client_gallery" == get_post_type( $parent ) ) {
        $mydir         = '/client_galleryy/'.$post->ID.'';
        $param['path'] = $param['basedir'] . $mydir;
        $param['url']  = $param['baseurl'] . $mydir;
    }



   return $param;


}

Try it it should work ...

4
  • This doesnt work. doesnt appear to be able to get the post id.
    – knmsuser
    Nov 23, 2016 at 18:21
  • @knmsuser , i have edited code can you please check, let me knw if it works
    – GKS
    Nov 23, 2016 at 18:44
  • this still didnt work. I'm not getting a post id still as far as I can tell. Where should I be putting this code? I've tried it in my plugin php file at the end of the file and in my functions.php file for my theme?
    – knmsuser
    Nov 24, 2016 at 13:16
  • you can either put it in plugin or functions.php file. it will execute . I have edited the code try now. it will put post id in session when wp loaded. @knmsuser
    – GKS
    Nov 24, 2016 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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