Can not modify wordpress default upload directory

53 views Asked by At

In my wordpress plugin I am trying to set a custom directory for my movies custom post images, based on the post name. I am using Cmb2 metaboxes. For instance, if the post is StarWars I want the images to be stored in uploads/movies/starwars/

The question has been adressed a 100 times, and most people use the filter 'upload_dir' to tackle the issue. For instance,

add_filter( 'upload_dir', 'my_custom_upload_directory' );
function my_custom_upload_directory( $args ){
    $id = $_REQUEST['post_id'];
    $parent = get_post( $id )->post_parent;
    $title = strtolower( get_the_title( $parent ) );

    // Check the post-type of the current post
    if( "movies" == get_post_type( $id ) || "movies" == get_post_type( $parent )) {
        $args['basedir'] = $args['basedir'] ."/movies/". $title;
        $args['baseurl'] = $args['baseurl'] ."/movies/". $title;
        }
    return $args;
}

Wherever I put this piece of code, $_REQUEST['post_id'] results in an error, as well as $_GET['post'] which is always null.

Because global $post is also null here, I can not use alternatives like define('UPLOADS', ... )

I have also tried to use the filter 'wp_handle_upload_prefilter' but I got the same issues as the ones I've aready mentionned.

It seems that other folks have the same problem though (https://wordpress.stackexchange.com/questions/366191/how-to-get-the-upcoming-post-id-from-front-end)

Does anyone have a clue to help me deal with this problem ? Thanks in advance for your help

0

There are 0 answers