在某个cpt更改上传目录文件夹但无法更改回来

时间:2015-03-05 15:30:09

标签: upload wordpress-plugin wordpress custom-post-type

我尝试使用upload_dir过滤器

我用这个函数检查当前的CPT

    function get_current_post_type() {
    global $post, $typenow, $current_screen;

    //we have a post so we can just get the post type from that
    if ( $post && $post->post_type ) {
        return $post->post_type;
    } //check the global $typenow - set in admin.php
    elseif ( $typenow ) {
        return $typenow;
    } //check the global $current_screen object - set in sceen.php
    elseif ( $current_screen && $current_screen->post_type ) {
        return $current_screen->post_type;
    } //lastly check the post_type querystring
    elseif ( isset( $_REQUEST['post_type'] ) ) {
        return sanitize_key( $_REQUEST['post_type'] );
    }

    //we do not know the post type!
    return NULL;
}

现在我想在名为“rsg_download”的某个cpt上更改'upload_dir'

add_action( 'admin_init', 'call_from_admin' );
function call_from_admin() {
   //Here i get the Current custom Post type is the Post type = "rsg_download" then i want upload in a other folder called "rsg-uploads"
    $currentCPT = get_current_post_type();
    if ( $currentCPT = 'rsg_download' ) {
        add_filter( 'upload_dir', 'change_upload_dir' );
    }
}

当我只使用

$currentCPT = get_current_post_type();
if ( $currentCPT = 'rsg_download' ) {
    add_filter( 'upload_dir', 'change_upload_dir' );
}

'change_upload_dir'函数被调用两次不知道为什么我也从'admin_init'用函数'call_from_admin'调用它,并且它只调用一次这么好

我转到我的CPT“rsg_download”并且uploade文件位于wp-content / uploads / rsg-uploads /的正确位置/到目前为止这是

现在我去“Pages”并上传一个文件,但我希望这些文件不在/ rsg-upload中但在默认路径中

更改upload_dir的函数只应在自定义帖子类型为'rsg_download'时调用此函数:

  function change_upload_dir( $param ) {

    $mydir = '/rsg-uploads';
    $param['path'] = $param['basedir'] . $mydir;
    $param['url']  = $param['baseurl'] . $mydir;
    return $param;
}

1 个答案:

答案 0 :(得分:1)

我找到了!这只会在" rsg_download"上传时更改上传目录。 CPT

add_filter( 'wp_handle_upload_prefilter', 'rsg_pre_upload' );
function rsg_pre_upload( $file ) {
    add_filter( 'upload_dir', 'rsg_custom_upload_dir' );
    return $file;
}

function rsg_custom_upload_dir( $param ) {
    $id = $_REQUEST['post_id'];
    $parent = get_post( $id )->post_parent;
    if( "rsg_download" == get_post_type( $id ) || "rsg_download" == get_post_type( $parent ) ) {
        $mydir         = '/rsg-uploads';
        $param['path'] = $param['basedir'] . $mydir;
        $param['url']  = $param['baseurl'] . $mydir;
    }
    return $param;


}