Getting values of a custom taxonomy dropdown

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.

Read More
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 …

Related posts

Leave a Reply

1 comment

  1. get_user_by() receives user data not taxonomy terms. Since you are not dealing with real userdata you’ll have to use get_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:

    function taxonomy_dropdown() {
        wp_dropdown_categories( array(
            'name'       => 'alt_comment_user',
            'taxonomy'   => 'custom_authors',
            'hide_empty' => false
        ));   
    }
    add_action( 'comment_form_logged_in_after', 'taxonomy_dropdown' );
    add_action( 'comment_form_after_fields', 'taxonomy_dropdown' );
    
    function save_user_settings( $input ) {
        global $wpdb;
    
        if( current_user_can( 'moderate_comments' ) && isset( $_POST['alt_comment_user'] ) ) {
            $username = get_term_by( 'id', (int) $_POST['alt_comment_user'], 'custom_authors' );
            $my_fields = array(
                'comment_author' => $wpdb->escape( $username->name ),
                'user_ID'        => 0,
            );
    
            $input = $my_fields + $input;   
        }
        return $input;
    }
    add_filter( 'preprocess_comment', 'save_user_settings' );