是否仅为自定义帖子类型设置自定义上传路径?

时间:2013-04-14 作者:Xav

我有一个自定义的“客户端”帖子类型,希望通过管理员上传的这些帖子的所有图像/文件都能转到我服务器上的特定目录,但其他一切都保持正常。是否可以使用wp\\u upload\\u dir?

3 个回复
SO网友:Chris_O

您可以添加一个筛选器以上载\\u dir。这是我为一个项目编写的一个简单类。使用protected $filter_path 变量定义备用上载目录(*将与wp内容/上载相关)

class UGC_Attachment {
    protected $upload_dir;
    protected $upload_url;
    protected $filter_path = \'/relative_path_from_wp-content/uploads\';

    function __construct() {
        $dir = wp_upload_dir();
        $this->upload_dir = $dir[\'basedir\'] . $this->filter_path;
        $this->upload_url = $dir[\'baseurl\'] . $this->filter_path;
    }

    function upload_dir_filter( $upload ) {
        $target_path = $this->upload_dir;
        $target_url  = $this->upload_url;
        wp_mkdir_p( $target_path );
        $upload[\'path\'] = $target_path;
        $upload[\'url\']  = $target_url;

       return $upload;
    }
}
用法:

function prefix_upload_dir_filter( $post ) {
    if ( \'clients\' != get_post_type( $post )
        return;
    $filter = new UGC_Attachment();
    return add_filter( \'upload_dir\', array( &$filter, \'upload_dir_filter\' );
}
prefix\\u upload\\u dir\\u filter函数需要附加到具有可用$post对象或$post ID的操作或筛选器。您需要做更多的研究来找出这一部分,或者其他人可以插话。我的使用是一个完整的定制图像上传解决方案,从前端开始,我需要将公开上传的图像放置在临时目录中,该目录可以通过cron作业每晚清除。

SO网友:gonzalezea

像这样的事情可能会奏效,只要根据需要更改mycpt

add_filter(\'upload_dir\', \'mycpt_uploaddir\');

function mycpt_uploaddir( $param ){
    global $typenow;

    if (\'mycpt\' != $typenow)
        return $param;

    $mycpt = \'/mycpt\';

    $param[\'path\'] = $param[\'path\'] . $mycpt;
    $param[\'url\'] = $param[\'url\'] . $mycpt;
    return $param;
}

SO网友:kakoma

这非常有效:

add_filter( \'upload_dir\', \'custom_prefix_upload_dir\'  );

        function custom_prefix_upload_dir( $pathdata ) {
            global $current_user,$pagenow;
            if ( ( \'async-upload.php\' == $pagenow || \'media-upload.php\' == $pagenow ) && false !== strpos( wp_get_referer(),\'post_type=clients\' ) ) {
                $custom_dir = \'/my_custom_uploads\';
                if ( empty( $pathdata[ \'subdir\' ] ) ) {
                    $pathdata[ \'path\' ] = $pathdata[ \'path\' ] . $custom_dir;
                    $pathdata[ \'url\' ] = $pathdata[ \'url\' ] . $custom_dir;
                    $pathdata[ \'subdir\' ] = \'/kanzu_intug\';
                } else {
                    $new_subdir = $custom_dir . $pathdata[ \'subdir\' ];

                    $pathdata[ \'path\' ] = str_replace( $pathdata[ \'subdir\' ], $new_subdir, $pathdata[ \'path\' ] );
                    $pathdata[ \'url\' ] = str_replace( $pathdata[ \'subdir\' ], $new_subdir, $pathdata[ \'url\' ] );
                    $pathdata[ \'subdir\' ] = str_replace( $pathdata[ \'subdir\' ], $new_subdir, $pathdata[ \'subdir\' ] );
                }
            }

            return $pathdata;
        }

结束