Skip to content

Instantly share code, notes, and snippets.

@TimBHowe
Last active May 24, 2022 16:21
Show Gist options
  • Save TimBHowe/6673252 to your computer and use it in GitHub Desktop.
Save TimBHowe/6673252 to your computer and use it in GitHub Desktop.
Add "Company" field to WordPress user account and add sortable company column to the user backend.
//add&remove field from user profiles - sorce:http://davidwalsh.name/add-profile-fields
function modify_contact_methods($profile_fields) {
// Add new fields
$profile_fields['company'] = 'Company';
// Remove old fields
//unset($profile_fields['aim']);
return $profile_fields;
}
add_filter('user_contactmethods', 'modify_contact_methods');
//Add the colum to the user backend
function user_sortable_columns( $columns ) {
$columns['company'] = 'Company';
return $columns;
}
add_filter( 'manage_users_sortable_columns', 'user_sortable_columns' );
//alter the user query and sorts whole list by company
function status_order_in_user_query($query){
if('Company'==$query->query_vars['orderby']) {
$query->query_from .= " LEFT JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id AND meta_key = 'company'";
$query->query_orderby = " ORDER BY wp_usermeta.meta_value ".($query->query_vars["order"] == "ASC" ? "asc " : "desc ");//set sort order
}
}
add_action('pre_user_query', 'status_order_in_user_query');
//makes the user meta searchable and returen results- source: http://www.tomauger.com/2012/tips-and-tricks/expanded-user-search-in-wordpress
function extended_user_search( $user_query ){
// Make sure this is only applied to user search
if ( $user_query->query_vars['search'] ){
$search = trim( $user_query->query_vars['search'], '*' );
if ( $_REQUEST['s'] == $search ){
global $wpdb;
$user_query->query_from .= " JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id";
$user_query->query_where = 'WHERE 1=1' . $user_query->get_search_sql( $search, array( 'user_login', 'user_email', 'user_nicename', 'meta_value' ), 'both' );
}
}
}
add_action( 'pre_user_query', 'extended_user_search' );
//add columns to User panel list page
function add_user_columns( $defaults ) {
$defaults['company'] = __('Company', 'user-column');
return $defaults;
}
add_filter('manage_users_columns', 'add_user_columns', 15, 1);
//Print the user data in the new column
function add_custom_user_columns($value, $column_name, $id) {
if( $column_name == 'company' ) {
return get_the_author_meta( 'company', $id );
}
}
add_action('manage_users_custom_column', 'add_custom_user_columns', 15, 3);
@sherryw1022
Copy link

Hello, I added the code above to my theme function file and I don't see this field in each user profile or as a column in users.php what do I need to do? thx

@jstneti01
Copy link

Thank you so much for this snippet. It works like a charm :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment