Custom upload directory per CPT; when removed, file not deleted

I have this code in functions.php that organize media upload according to its Custom Post Type (CPT).

So all images uploaded to a “Product” CPT will be inside wp-content/uploads/product directory.

add_filter("upload_dir", function ($args) {
  $id = (isset($_REQUEST["post_id"]) ? $_REQUEST["post_id"] : "");

  if($id) {
    $newdir = "https://wordpress.stackexchange.com/" . get_post_type($id);

    // remove default dir
    $args["path"] = str_replace( $args["subdir"], "", $args["path"]);
    $args["url"] = str_replace( $args["subdir"], "", $args["url"]);

    // assign new dir
    $args["subdir"] = $newdir;
    $args["path"] .= $newdir; 
    $args["url"] .= $newdir;

    return $args;
  }
});

It works well, except when I delete the media, the file is still there (the database entry is deleted just fine).

I figured I need to filter the media deletion too, but can’t seem to find the right way. Have anyone successfully set this up?

Thanks

EDIT

I tried adding conditional to use default folder when the post type is post.

if(get_post_type($id) === "post") {
  return $args;
} else {
  ...
}

Deleting a Post’s media also won’t delete the file.

2 s
2

A small mistake, the return should be outside if

add_filter("upload_dir", function ($args) {
  $id = (isset($_REQUEST["post_id"]) ? $_REQUEST["post_id"] : "");

  if($id) {
    $newdir = "https://wordpress.stackexchange.com/" . get_post_type($id);
    ...
  }

  return $args;
});

Leave a Comment