Make display name unique

As far as I’m aware, all you can do is filter the display name via pre_user_display_name and check if it already exists. Unfortunately WP_User_Query doesn’t support querying by display_name, so we also have to add to the WHERE clause via pre_user_query. Additionally, there is no elegant way I can think of to handle the case where the display_name already exists beyond returning nothing, since we don’t know via the filter what user this potential display name is attached to. or maybe I’m just tired and missing something obvious! Anyway, here’s a quick test I created:

class wpa82239_display_name {
    private $display_name;

    public function __construct(){
        add_filter( 'pre_user_display_name', array( $this, 'display_name_filter' ) );
    }

    public function display_name_filter( $display_name ){

        $this->display_name = $display_name;
        add_action( 'pre_user_query', array( $this, 'user_query_filter' ) );
        $args = array(
            'number' => 1,
            'fields' => 'ID'
        );
        $user_search = new WP_User_Query( $args );
        remove_action( 'pre_user_query', array( $this, 'user_query_filter' ) );

        if( 0 == $user_search->total_users )
            return $display_name;

        return null;
    }

    public function user_query_filter( $query ){
        global $wpdb;
        $query->query_where .= $wpdb->prepare(
            " AND $wpdb->users.display_name = %s",
            $this->display_name
        );
    }

}
$wpa82239_display_name = new wpa82239_display_name();

Leave a Comment