Home › Forums › General Issues › Pre populate user field with current user
The answer is probably easy but makes my head spinning,
I have a user select field that I would like to pre populate with current user adding a new post. What filter/or action would I use? And is it possible to have the “nice name” (nickname) in the dropdown list?
Hi @kru-x
you should be able to achieve that with one of these filters: https://www.advancedcustomfields.com/resources/#filters
Phil
Hi Phil,
Been in to those one and poked around but that’s what makes my head spin, not too confident in PHP yet, still learning. which filter would be suitable for pre populating user value and how can I get get it to show the nickname?
Thank’s
A user field and I would like to pre populate that one with the “author” (current user)
Hey @kru-x
I would look into https://www.advancedcustomfields.com/resources/acf-load_field/. Just print_r($field); exit;
in your function, and that’ll show you all the data that’s in the object.
You should be able to use wp_get_current_user()
to get the current User’s id (https://codex.wordpress.org/wp_get_current_user)
Let me know if that helps (i haven’t tested this, just trying to give you a start).
Phil
Hi Phil,
Thank’s for the push in the right direction but the acf-load, did not work as I did it on a new post, it gave me the field before it was loaded (as the name suggest I suppose :-)) and messed up the load of all users.
Maybe it has a solution but I achieved what I needed with the below one (don’t know if it is “programatically correct” but it works for me) if anyone else have the same problem:
function my_prepare_field( $field ) {
$screen = get_current_screen();
$user = wp_get_current_user();
$user = $user -> ID;
//check if post type is new and of a specific post type
if ( ‘add’ === $screen->action && “my_post_type” === $screen->post_type ){
$field [‘value’]= $user; //set user to current user
return $field;
}
else {
return $field;
}
}
add_filter(‘acf/prepare_field/name=my_post_type’, ‘my_prepare_field’);
The topic ‘Pre populate user field with current user’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.