I have a custom taxonomy dropdown (custom_authors
) which is displayed in the comments form when logged in to select a different author than the logged in one.
add_action( 'comment_form_logged_in_after', 'taxonomy_dropdown' );
add_action( 'comment_form_after_fields', 'taxonomy_dropdown' );
function taxonomy_dropdown() {
wp_dropdown_categories( array(
'name' => 'alt_comment_user',
'taxonomy' => 'custom_authors',
'hide_empty' => false
));
}
The following function should save the selected value (name
and id
) but I donât manage to get it to work.
add_filter('preprocess_comment', 'save_user_settings' );
function save_user_settings($input) {
if(current_user_can('moderate_comments') && isset($_POST['alt_comment_user'])){
$user = get_user_by('id', (int)$_POST['alt_comment_user']);
$my_fields = array(
'comment_author' => $user->name,
'user_ID' => $user->ID,
);
// escape for db input
foreach($my_fields as &$field)
$field = $GLOBALS['wpdb']->escape($field);
$input = $my_fields + $input;
}
return $input;
}
The output I get the name “Anonymous” as comment author.
Can somebody help how I get the correct value from the taxonomy dropdown? I think I have to change especially this line get_user_by('id', (int)$_POST['alt_comment_user']);
to get_term_by but I donât know how â¦
get_user_by()
receives user data not taxonomy terms. Since you are not dealing with real userdata you’ll have to useget_term_by()
to receive the term name. You would use it like this:$username = get_term_by( 'id', (int) $_POST['alt_comment_user'], 'custom_authors' );
Fixed code: