Support

Account

Home Forums ACF PRO Gallery field hide media library

Solved

Gallery field hide media library

  • On a front end form using the Gallery field I need to be able to either hide the media library or else limit the images in the media library to only images uploaded by the logged in user. I was able to hide the media library on the Image field by adding the 'uploader' => 'basic' parameter to the acf_form() function, but this doesn’t work for the Gallery field.

    Thanks

  • What type of users will be using this front end form? Have you tried logging into your site as that type of user? Does that type of user have access to the media library? If not then the gallery field isn’t going to work for them and you’ll need to provide them with an alternate to the gallery.

    Assuming that they do have access to the media library you can limit the images that they see to only the ones they uploaded by using a pre_get_posts filter.

    
    add_filter('pre_get_posts', 'limit_gallery_to_user');
    function limit_gallery_to_user($query) {
      if (is_admin() || 
          !isset($query->query_vars['post_type']) ||
          $query->query_vars['post_type'] != 'attachment') {
        return;
      }
      $user_id = get_current_user_id();
      $query->set('author', $user_id);
    }
    

    If they don’t have access to the medial library and the gallery does not work you will probably need to use a repeater field with image fields and then transfer the images to the gallery using an acf/save_post filter.

  • I created a custom user role with capabilities similar to ‘author’. The code you posted limited the images visible in the Gallery field itself but not in the media library. I was able to get it working with the following:

    function restrict_media_library_to_current_user( $wp_query_obj ) {
    
    	if ( ! current_user_can( 'level_5' ) ) {
    
    		global $current_user, $pagenow;
    
    		if (  ! is_a( $current_user, 'WP_User' ) || 'admin-ajax.php' != $pagenow || $_REQUEST['action'] != 'query-attachments' ) {
    			return;
    		}
    
    		$wp_query_obj->set( 'author', $current_user->ID );
    
    		return;
    	}
    }
    
    add_action( 'pre_get_posts', 'restrict_media_library_to_current_user' );
  • It could be that my code was failing because the AJAX request is considered to be in the admin, I hadn’t thought of that. You’re code may also limit the images that you see when you’re working in the admin.

  • The if ( ! current_user_can( 'level_5' ) ) { conditional will prevent this from affecting administrators. For other users everything they will do is on the front end, but if they did have admin access it would be good to limit the images there as well.

    Thanks

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Gallery field hide media library’ is closed to new replies.