Support

Account

Home Forums Feature Requests Restrict Relationship Fields Choices to Current User

Solved

Restrict Relationship Fields Choices to Current User

    • Johann

    • February 4, 2015 at 4:32 am

    To build multi-user webapps with acf_form() there is a need of an option to restrict the relationship fields posts/choices to the current logged-in user.

    • Johann

    • February 23, 2015 at 5:42 am

    This solves it.
    http://www.advancedcustomfields.com/resources/acf-fields-relationship-query/

    function my_relationship_query( $args, $field, $post ) {
        // get posts for current logged in user
        $args['author'] = get_current_user_id();
    
        return $args;
    }
    add_filter('acf/fields/relationship/query/key=<field_key>', 'my_relationship_query', 10, 3);
    • sshilo

    • March 1, 2015 at 6:09 am

    should this go in functions.php? I add the field_key and could not get it to work (shows all posts, or CPT)

    I also tried name with similar results.

    I hate writing this because I know this isn’t a lot to go on. Any idea of what I could look at?

    After attempting to use more basic functions, I can’t seem to use any of them. if I use the_field the page crashes immediately as it’s called. I’m sure I’m missing something very basic.

    • mica

    • February 10, 2020 at 2:51 am

    Hi folk,
    I had the quite similar issue. I needed also to grant a full access to “editor” & “administrator”.
    Here is the code inserted in the functions.php file

    function modify_field( $args, $field,$post) {
    	if( !check_user_role(array('editor','administrator')) ){
    		$args['author'] = get_current_user_id();
    	}
        return $args;
    }
    
    	add_filter( 'acf/fields/post_object/query/key=field_XXX..XXX', 'modify_field', 10, 3 );
    
    /* @src & @credits https://wp-mix.com/wordpress-check-user-roles/ */
    function check_user_role($roles, $user_id = null) {
    	if ($user_id) $user = get_userdata($user_id);
    	else $user = wp_get_current_user();
    	if (empty($user)) return false;
    	
    	foreach ($user->roles as $role) {
    		if (in_array($role, $roles)) {
    			return true;
    		}
    	}
    	return false;
    }
Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.