Skip to content

Instantly share code, notes, and snippets.

@apathetic
Created September 6, 2012 00:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apathetic/3648737 to your computer and use it in GitHub Desktop.
Save apathetic/3648737 to your computer and use it in GitHub Desktop.
Wordpress: add radio button to admin Users table
/*
* Add a column to the Users table, with a radio button
* The radio button updates a usermeta field via ajax
*/
add_filter( 'manage_users_columns', 'add_display_column');
function add_display_column( $columns){
$columns['display_as'] = 'Display as';
return $columns;
}
add_filter('manage_users_custom_column', 'add_display_value', 50, 3); // we use a lower priority (higher number, 50) here so as to fire after the custom_metadata plugin, which interferes. Damn plugin
function add_display_value( $value, $column_name, $user_id ){
$user = get_userdata( $user_id );
switch ($column_name) {
case 'display_as' :
$buttons = '<label><input type="radio" class="save_display" name="display_as-'.$user_id.'" value="team" '.checked( 'team' == $user->display_as, true, false ).'> Team member</label><br />'.
'<label><input type="radio" class="save_display" name="display_as-'.$user_id.'" value="friend" '.checked( 'friend' == $user->display_as, true, false ).'> BFF</label>';
return $buttons;
break;
default:
}
return $value;
}
add_action('wp_ajax_save_display_value', 'save_display_value');
function save_display_value(){
$value = $_POST['value'];
$user_id = $_POST['userid'];
update_usermeta($user_id, 'display_as', $value );
// echo 'success';
exit();
}
add_action('admin_footer', 'save_display_value_javascript');
function save_display_value_javascript() {
global $current_screen;
if ($current_screen->id != 'users') return; ?>
<script type="text/javascript">
jQuery('.save_display').click(function() {
var value = jQuery(this).val();
var userid = jQuery(this).attr('name').split('-')[1];
jQuery.post('<?php echo admin_url("admin-ajax.php") ?>', { action: 'save_display_value', userid: userid, value: value }, function( response ) { /* do nothing */ } );
});
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment