Support

Account

Home Forums Backend Issues (wp-admin) Not compatible with this code?

Solved

Not compatible with this code?

  • Hey there!

    I’m currently using ACF with the Flexible Content add-on. What an awesome plugin!

    However, there’s a conflict with some other code I use. I have several user roles (e.g. editors, contributors etc) who should only have access to their own content (and not posts & pages that others created).

    The following code makes sure that everyone only has access to their own content:

    function posts_for_current_author($query) {
    global $user_level;
    
    if($query->is_admin && $user_level < 5) {
    	
    		add_action('add_meta_boxes', 'yoast_is_toast', 99);
    		global $user_ID;
    		$query->set('author', $user_ID);
    		
    		unset($user_ID);
    	}
    unset($user_level);
    
    return $query;
    }
    add_filter('pre_get_posts', 'posts_for_current_author');
    

    This code works. However, it also makes sure that all custom fields (generated with ACF) don’t appear for all user roles lower than admin. I’m expecting that it’s because these “custom fields” are created by another user account (e.g. the admin account).

    Unfortunately I’m not much of a coder myself (found the code above online), so now I’m desperately looking for a solution..

    Any thoughts?

    Thanks in advance,

    Wilco

  • Hi @wdekreij

    You need to allow the ‘acf’ post_Type as an excerption.

    The $query parameter will most likely contain a ‘post_type’ value. If that value == ‘acf’, you should allow this ( don’t change the $query )

  • Woops – I checked the “this solved it”-button, but I’m still struggling with it.

    I’m not much of a coder, but I tried various ways of coding and thus far without luck.

    Right now I’ve changed it to

    function posts_for_current_author($query) {
    global $user_level;
    
    if($query->is_admin && $user_level < 5 && get_post_type() != "acf") {	
    	
    		global $user_ID;
    		$query->set('author', $user_ID);
    		
    		unset($user_ID);
    	}
    unset($user_level);
    
    return $query;
    }
    
    add_filter('pre_get_posts', 'posts_for_current_author');
    

    But unfortunately that doesn’t change a thing.. Any thoughts?

  • Hi @wdekreij

    I don’t think the get_post_type() will work.

    
    The $query parameter will most likely contain a ‘post_type’ value. If that value == ‘acf’, you should allow this ( don’t change the $query )
    
  • Then how can I retrieve that value, you think?

  • I would use something like this:

    
     if( isset($query->query_vars['post_type']) &&  $query->query_vars['post_type'] == 'acf' )
    {
    	return $query;
    }
    

    Tip: Always debug your params and variables to find out what you have to work with!

  • Hi

    Interestingly only a day later than the last post I came looking for an answer to exactly the same question. I seem to have solved the problem, well at least for myself I have in this way…

    function posts_for_current_author($query) {
    	
    	if( !$query->is_admin )
    		return $query;
    		
    	$screen = get_current_screen();
    	
    	if ($screen->base === 'post')
        		return $query;
    	
    	if( !current_user_can( 'moderate_comments' ) ) {
    		global $user_ID;
    		$query->set('author', $user_ID );
    		
    	}
    	return $query;
    }

    Essentially this checks to see if you are in admin

    Then the critical bit for ACF it looks to see if you are editing a page which is the screen->base === ‘post’ bit. That will return the standard query since the mod to user_ID in the query loses the ACF fields.

    Like I said this works here and I should be grateful if you can let me know if it works for you too.

    By the way I have additional code to change the headings on the list of posts since it shows all and published even though you can’t see them.

    All the best

  • I replace my code with yours, but this code doesn’t work unfortunately.

    Using your code, users are able to see others’ posts.

    So it does fix the issue I had (advanced custom fields not showing), but now it doesn’t do the core thing it was supposed to do..

  • My bad – your code is working 🙂 Thanks a million!

    The only thing that I still need to fix, is the fact that it’s showing incorrect number (See http://d.pr/i/Yw5f).

    I know it has nothing to do with ACF: you already helped me with that (and I just purchased my 2nd add-on, btw!). But IF you had any idea on how to get this done, feel free to share it with me and blow my mind regarding your level of support 😉

  • when I checked my code it was not working although I was sure it had been before!!!

    Anyhow with a combination of things this is definitely working on my site now, you need the filters to modify the numbers of posts shown at the top of the list of posts screen.

    function listings_for_current_author($query) {
    	
    	if( !$query->is_admin )
    		return $query;
    		
    	if( isset($query->query_vars['post_type']) &&  $query->query_vars['post_type'] == 'acf' )
    {
    	return $query;
    }
    		
    	
    	if( !current_user_can( 'moderate_comments' ) ) {
    		global $user_ID;
    		$query->set('author', $user_ID );
    		add_filter('views_edit-site_listings', 'fix_listing_counts');
                    add_filter('views_upload', 'fix_listing_media_counts');
    	}
    	return $query;
    }
    
    add_action('pre_get_posts', 'listings_for_current_author');
    
    // Fix post counts
    function fix_listing_counts($views) {
        global $current_user, $wp_query;
    	/*
    	unset($views['all']);
                unset($views['publish']);
                unset($views['trash']);
    	*/
    	
    	
        unset($views['mine']);
        $types = array(
            array( 'status' =>  NULL ),
            array( 'status' => 'publish' ),
            array( 'status' => 'draft' ),
            array( 'status' => 'pending' ),
            array( 'status' => 'trash' )
        );
        foreach( $types as $type ) {
            $query = array(
                'author'      => $current_user->ID,
                //'post_type'   => 'post',
    			'post_type'   => 'site_listings',
                'post_status' => $type['status']
            );
            $result = new WP_Query($query);
            if( $type['status'] == NULL ):
                $class = ($wp_query->query_vars['post_status'] == NULL) ? ' class="current"' : '';
                $views['all'] = sprintf(__('<a href="%s"'. $class .'>All <span class="count">(%d)</span></a>', 'all'),
                    admin_url('edit.php?post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'publish' ):
                $class = ($wp_query->query_vars['post_status'] == 'publish') ? ' class="current"' : '';
                $views['publish'] = sprintf(__('<a href="%s"'. $class .'>Published <span class="count">(%d)</span></a>', 'publish'),
                    admin_url('edit.php?post_status=publish&post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'draft' ):
                $class = ($wp_query->query_vars['post_status'] == 'draft') ? ' class="current"' : '';
                $views['draft'] = sprintf(__('<a href="%s"'. $class .'>Draft'. ((sizeof($result->posts) > 1) ? "s" : "") .' <span class="count">(%d)</span></a>', 'draft'),
                    admin_url('edit.php?post_status=draft&post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'pending' ):
                $class = ($wp_query->query_vars['post_status'] == 'pending') ? ' class="current"' : '';
                $views['pending'] = sprintf(__('<a href="%s"'. $class .'>Pending <span class="count">(%d)</span></a>', 'pending'),
                    admin_url('edit.php?post_status=pending&post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'trash' ):
                $class = ($wp_query->query_vars['post_status'] == 'trash') ? ' class="current"' : '';
                $views['trash'] = sprintf(__('<a href="%s"'. $class .'>Trash <span class="count">(%d)</span></a>', 'trash'),
                    admin_url('edit.php?post_status=trash&post_type=site_listings'),
                    $result->found_posts);
            endif;
        }
    	
        return $views;
    }
    
    // Fix media counts
    function fix_listing_media_counts($views) {
        global $wpdb, $current_user, $post_mime_types, $avail_post_mime_types;
        $views = array();
        $_num_posts = array();
        $count = $wpdb->get_results( "
            SELECT post_mime_type, COUNT( * ) AS num_posts 
            FROM $wpdb->posts 
            WHERE post_type = 'attachment' 
            AND post_author = $current_user->ID 
            AND post_status != 'trash' 
            GROUP BY post_mime_type
        ", ARRAY_A );
        foreach( $count as $row )
            $_num_posts[$row['post_mime_type']] = $row['num_posts'];
        $_total_posts = array_sum($_num_posts);
        $detached = isset( $_REQUEST['detached'] ) || isset( $_REQUEST['find_detached'] );
        if ( !isset( $total_orphans ) )
            $total_orphans = $wpdb->get_var("
                SELECT COUNT( * ) 
                FROM $wpdb->posts 
                WHERE post_type = 'attachment' 
                AND post_author = $current_user->ID 
                AND post_status != 'trash' 
                AND post_parent < 1
            ");
        $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
        foreach ( $matches as $type => $reals )
            foreach ( $reals as $real )
                $num_posts[$type] = ( isset( $num_posts[$type] ) ) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
        $class = ( empty($_GET['post_mime_type']) && !$detached && !isset($_GET['status']) ) ? ' class="current"' : '';
        $views['all'] = "<a href='upload.php'$class>" . sprintf( __('All <span class="count">(%s)</span>', 'uploaded files' ), number_format_i18n( $_total_posts )) . '</a>';
        foreach ( $post_mime_types as $mime_type => $label ) {
            $class = '';
            if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
                continue;
            if ( !empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
                $class = ' class="current"';
            if ( !empty( $num_posts[$mime_type] ) )
                $views[$mime_type] = "<a href='upload.php?post_mime_type=$mime_type'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), $num_posts[$mime_type] ) . '</a>';
        }
        $views['detached'] = '<a href="upload.php?detached=1"' . ( $detached ? ' class="current"' : '' ) . '>' . sprintf( __( 'Unattached <span class="count">(%s)</span>', 'detached files' ), $total_orphans ) . '</a>';
        return $views;
    }
    
  • Hmm – that count script isn’t working for me.. Anything else I need to change except for the post types (since you targeted “site_listings”).

  • oh yes, sorry… the filter call needs to be changed and the post type in the filter callback need to changed – in fact there is a bit where I commented out the post in the original – here is some changed code with comments as I can’t test it fully without setting up a new site for posts and creating users etc..

    function posts_for_current_author($query) {
    	
    	if( !$query->is_admin )
    		return $query;
    		
    	if( isset($query->query_vars['post_type']) &&  $query->query_vars['post_type'] == 'acf' )
    {
    	return $query;
    }
    		
    	
    	if( !current_user_can( 'moderate_comments' ) ) {
    		global $user_ID;
    		$query->set('author', $user_ID );
    
                    // filter for changing the numbers on the list
                    // its called for views_edit-xxx where xxx is the post/custom post type
    		add_filter('views_edit-post', 'fix_post_counts');
                    add_filter('views_upload', 'fix_media_counts');
    	}
    	return $query;
    }
    
    add_action('pre_get_posts', 'posts_for_current_author');
    
    // Fix post counts
    function fix_post_counts($views) {
        global $current_user, $wp_query;
    	
    	
    	
        unset($views['mine']);
        $types = array(
            array( 'status' =>  NULL ),
            array( 'status' => 'publish' ),
            array( 'status' => 'draft' ),
            array( 'status' => 'pending' ),
            array( 'status' => 'trash' )
        );
        foreach( $types as $type ) {
            $query = array(
                'author'      => $current_user->ID,
                // the post type/custom post type we are modifying
                'post_type'   => 'post',
    			
                'post_status' => $type['status']
            );
            $result = new WP_Query($query);
            if( $type['status'] == NULL ):
                $class = ($wp_query->query_vars['post_status'] == NULL) ? ' class="current"' : '';
                $views['all'] = sprintf(__('<a href="%s"'. $class .'>All <span class="count">(%d)</span></a>', 'all'),
                    admin_url('edit.php?post_type=post'),
                    $result->found_posts);
            elseif( $type['status'] == 'publish' ):
                $class = ($wp_query->query_vars['post_status'] == 'publish') ? ' class="current"' : '';
                $views['publish'] = sprintf(__('<a href="%s"'. $class .'>Published <span class="count">(%d)</span></a>', 'publish'),
                    admin_url('edit.php?post_status=publish&post_type=post'),
                    $result->found_posts);
            elseif( $type['status'] == 'draft' ):
                $class = ($wp_query->query_vars['post_status'] == 'draft') ? ' class="current"' : '';
                $views['draft'] = sprintf(__('<a href="%s"'. $class .'>Draft'. ((sizeof($result->posts) > 1) ? "s" : "") .' <span class="count">(%d)</span></a>', 'draft'),
                    admin_url('edit.php?post_status=draft&post_type=post'),
                    $result->found_posts);
            elseif( $type['status'] == 'pending' ):
                $class = ($wp_query->query_vars['post_status'] == 'pending') ? ' class="current"' : '';
                $views['pending'] = sprintf(__('<a href="%s"'. $class .'>Pending <span class="count">(%d)</span></a>', 'pending'),
                    admin_url('edit.php?post_status=pending&post_type=post'),
                    $result->found_posts);
            elseif( $type['status'] == 'trash' ):
                $class = ($wp_query->query_vars['post_status'] == 'trash') ? ' class="current"' : '';
                $views['trash'] = sprintf(__('<a href="%s"'. $class .'>Trash <span class="count">(%d)</span></a>', 'trash'),
                    admin_url('edit.php?post_status=trash&post_type=post'),
                    $result->found_posts);
            endif;
        }
    	
        return $views;
    }
    
  • Since I’m using it for the post type “course”, I changed the post_type=post into post_type=course.

    However, the count still doesn’t work (it still counts everything).

    Also, the 1st part of your code (that you last posted) doesn’t work (to show only the authors content) – while an earlier example of you did work – so I used the code below for the first part and added the “Fix post counts” count only.

    What I’m currently using (working code).

    // So authors can only see their own content (e.g. courses etc)
    function posts_for_current_author($query) {
    	
    	if( !$query->is_admin )
    		return $query;
    		
    	$screen = get_current_screen();
    	
    	if ($screen->base === 'post')
        		return $query;
    	
    	if( !current_user_can( 'activate_plugins' ) ) {
    		global $user_ID;
    		$query->set('author', $user_ID );
    		
    	}
    	return $query;
    	
    	
    }
    
    add_filter('pre_get_posts', 'posts_for_current_author');

    I haven’t been able to get the count correct, see http://d.pr/i/Ijhs.

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

The topic ‘Not compatible with this code?’ is closed to new replies.