前端的 WordPress 媒体上传被管理员重定向阻止

问题描述 投票:0回答:1

我正在使用 wp-editor 让用户编写文本和上传媒体。

我添加了一个脚本,可以防止用户在未以管理员身份登录的情况下进入后端。

这是脚本:

function yproject_admin_init() {
   if (! current_user_can( 'activate_plugins' )) {
     wp_redirect(site_url());
     exit();
   }
}
add_action( 'admin_init', 'yproject_admin_init' );

问题是:对于非管理员用户,当他们尝试上传文件时,文件似乎已上传,但最后收到消息:“上传时发生错误。请稍后重试。”

如果我删除“重定向”和“退出”行,它就可以正常工作(但显然,用户访问管理端)。

我可以添加哪些测试来防止这种情况发生?

php wordpress upload editor media
1个回答
0
投票

我很感谢“Emilien”十多年前在本页顶部发布了这个问题,因为它让我们发现是我们的functions.php中的管理员重定向功能阻止了非管理员用户访问媒体图书馆,不一定是他们的滚动能力。然后上面的“manishie”将链接(请参阅上面他的注释中的链接)发布到另一篇文章,该文章实际上解决了我们的问题。我在这两个地方都发布了这个解决方案。因此,基于“HWD”在另一篇文章中提供的基本解决方案,这里重写了functions.php中的nonAdminRedirect()函数。 (撰写本文时 WordPress 6.4.2。)

function nonAdminRedirect() {
  if( $_SERVER['PHP_SELF'] == '/wp-login.php' ){
    return true; // allow users to login

  } else if ( 
      $_SERVER['PHP_SELF'] == '/wp-admin/admin-ajax.php' || 
      $_SERVER['PHP_SELF'] == '/wp-admin/post.php') {   
    // 1st condition allows user to see photos or upload files in media library 
    // 2nd condition allows user to click "Edit Image" option when photo is selected;

    $roles_array = ['administrator', 'gw-contributor'];
    // Check if the user is one of the specified roles
    $user_has_allowed_role = false;
    foreach ($roles_array as $allowed_role) {
      if (in_array($allowed_role, $current_user->roles)) {
        $user_has_allowed_role = true;
        break;
      }
    }

    if ($user_has_allowed_role) {
      return true;
    } else {
      wp_safe_redirect(site_url());
      exit;
    }

  } else { 
    // otherwise this is not-a-login && not-an-ajax-call
    if(current_user_can('administrator') != 'administrator'){
    // Non-admin access to dashboard or other admin
      wp_safe_redirect(site_url());
      exit;
    } 
  }
}
add_action( 'login_form_login', 'nonAdminRedirect' );
add_action( 'admin_init', 'nonAdminRedirect', 1 );

最后说明:这些是我们在创建的名为“gw-contributor”的特殊卷中分配的功能,用于添加/编辑/删除特殊帖子类型“greatworkers”:edit_greatworkers、publish_greatworkers、delete_greatworkers、read、upload_files、edit_files、edit_posts。进入媒体库后,“编辑图像”链接需要“edit_posts”才能工作。

© www.soinside.com 2019 - 2024. All rights reserved.