WordPress的自定义元框和字段:根据用户编辑页面更改目录上载

时间:2014-08-07 16:14:37

标签: php wordpress custom-fields meta-boxes

我使用CMB script (Custom Meta Boxes and Fields for WordPress)为自定义角色为cliente的不同用户上传文件。

我能够显示字段并使它们起作用(尽管它们仅在编辑用户时出现,而不是在创建时出现,但这是另一个问题)。我现在想要实现的是将文件上传到不同用户的不同文件夹。

以下是代码:

// Here we add a new user role, "cliente"
add_role( 'cliente', 'Cliente' );

add_filter('wp_handle_upload_prefilter', 'my_upload_prefilter');
add_filter('wp_handle_upload', 'my_upload_postfilter');

function my_upload_prefilter( $file ) {
    add_filter('upload_dir', 'custom_upload_dir');
    return $file;
}

function my_upload_postfilter( $fileinfo ) {
    remove_filter('upload_dir', 'custom_upload_dir');
    return $fileinfo;
}

function custom_upload_dir( $path ) {
    global $pagenow;

    // Check if we are on the user-edit.php page
    if ( $pagenow == 'user-edit.php' && isset($_GET['user_id']) ) {
        // Set the role we want to change the path for
        $role_to_check = 'cliente';
        // Get a bunch of user info for later use
        $user_id = filter_var( $_GET['user_id'], FILTER_SANITIZE_NUMBER_INT );
        $meta = get_user_meta($user_id);
        $roles = unserialize($meta['wp_capabilities'][0]);
        // If we are on the chosen role page, set the $customdir to first_name + last_name
        if ( !empty($roles[$role_to_check]) ) {
            $customdir = '/' . $meta['first_name'][0] . $meta['last_name'][0];
        }
    } else {
        // Here we are not on the user-edit.php page. This is just a check to prove that WP is not recognizing the correct page, maybe because we are doing an Ajax call when this function is called. Confusing.
        $customdir = '/did-not-work';
    }

    // If there is any error, just return the $path and abort the rest.
    if ( !empty( $path['error'] ) ) {
        return $path;
    }

    // Here we set the new $path with the $customdir set above
    $path['path']    = str_replace($path['subdir'], '', $path['path']); //remove default subdir (year/month)
    $path['url']     = str_replace($path['subdir'], '', $path['url']);      
    $path['subdir']  = $customdir;
    $path['path']   .= $customdir; 
    $path['url']    .= $customdir; 
    return $path;

}

从我运行的几个检查看起来我的代码确实检索了用户ID和数据库中存储的数据,但在上传图像时它没有检测到它。这可能与我们通过Ajax上传图像的事实有关吗?

为了清楚起见,我不希望基于当前登录用户进行上传,但是对于用户我作为超级管理员使用edit-user.php页面进行编辑。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我自己想通了。首先是正确的代码,然后是解释:

// Here we add a new user role, "cliente".
add_role( 'cliente', 'Cliente' );

// These are the filters we need to add in order to modify the default upload path.
add_filter('wp_handle_upload_prefilter', 'my_upload_prefilter');
add_filter('wp_handle_upload', 'my_upload_postfilter');

function my_upload_prefilter( $file ) {
    add_filter('upload_dir', 'custom_upload_dir');
    return $file;
}
function my_upload_postfilter( $fileinfo ) {
    remove_filter('upload_dir', 'custom_upload_dir');
    return $fileinfo;
}

function custom_upload_dir( $path ) {
    // When uploading, the file gets sent to upload_async.php, so we need to take the referral page in order to be able to get the user_id we need. We then take the query string, pass it through parse_str and store it in a $query_array. Took me a while to figure it out, but now it works like a charm.
    $actual_page = $_SERVER['HTTP_REFERER'];
    parse_str( parse_url($actual_page, PHP_URL_QUERY), $query_array );

    // Check if we are uploading from the user-edit.php page.
    if ( strpos($actual_page, 'user-edit.php') ) {
        // Set the role we want to change the path for.
        $role_to_check = 'cliente';
        // Get a bunch of user info for later use
        $user_id = filter_var( $query_array['user_id'], FILTER_SANITIZE_NUMBER_INT );
        $meta = get_user_meta( $user_id );
        $roles = unserialize( $meta['wp_capabilities'][0] );
        // If we are on the chosen role page, set the $customdir to first_name + last_name
        if ( !empty($roles[$role_to_check]) ) {
            $customdir = '/docs/' . $meta['first_name'][0] . $meta['last_name'][0];

            // If there is any error, just return the $path and abort the rest.
            if ( !empty( $path['error'] ) ) {
                return $path;
            }

            // Here we set the new $path with the $customdir set above
            $new_subdir = $customdir . $path['subdir'];
            $path['path']    = str_replace( $path['subdir'], $new_subdir, $path['path'] );
            $path['url']     = str_replace( $path['subdir'], $new_subdir, $path['url'] );
            $path['subdir']  = $new_subdir;
            return $path;
        }
    } else {
        // We are not uploading from user-edit.php, so go ahead as per default.
        return $path;
    }
}

问题是,当通过Ajax上传时,$pagenow正确存储了async-upload.php页面,而不是我们所在的网址。我只需要通过php {{检索引荐页面1}}(请注意$_SERVER['HTTP_REFERER']错字是因为http规范中遗留的错误,有趣的东西)。

请注意,PHP规范不鼓励使用referer,因为它可能会根据服务器配置产生意外结果,但在这种情况下,我应该完全控制服务器,所以它应该不是问题。如果您遇到任何问题,我建议您检查一下。

一旦我有了正确的网址,我就可以解析它并检查我们是否在HTTP_REFERER,如果我们在,请从查询字符串中获取user-edit.php并从那里继续。

我花了一些时间来弄明白,但事后看来这很容易。

希望将来帮助其他人。