Skip to content

Instantly share code, notes, and snippets.

@alanef
Last active May 4, 2019 14:18
Show Gist options
  • Select an option

  • Save alanef/1ff70dc3e22d73ca45e2f3985c7dff94 to your computer and use it in GitHub Desktop.

Select an option

Save alanef/1ff70dc3e22d73ca45e2f3985c7dff94 to your computer and use it in GitHub Desktop.

Plugin to display user roles' names in a Shortcode

download the zip ( top right ) and rename the file to something sensible line show-user-roles.zip and install in the normal way or

create a folder in your plugins directory , e.g. show-user-roles add the index.php to the folder activate the plugin

use the shortcode [showmyroles] Arguments: delimiter ( default
) e.g. [showmyroles delimiter=' | ']]

<?php
/*
Plugin Name: Show User Roles
Plugin URI: https://fullworks.net/
Description: Show User Roles
Version: 2.1
Author: Alan
Author URI: https://fullworks.net/
License: GPL2
*
* No warranty or liability accepted as per GPL
*
* Shortcode to display a user's roles' names
*
* Usage:
* [showmyroles delimiter="<br>"]
*
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
add_shortcode( 'showmyroles', function ( $atts ) {
if ( ! is_user_logged_in() ) {
return "";
}
$a = shortcode_atts( array(
'delimiter' => '<br>',
), $atts );
global $wp_roles;
$roles = array_filter( $wp_roles->roles, function ( $key ) {
$user = get_userdata( get_current_user_id() );
if ( property_exists( $user, 'roles' ) ) {
if ( in_array( $key, $user->roles ) ) {
return true;
}
}
return false;
}, ARRAY_FILTER_USE_KEY );
$names = array_column( $roles, 'name' );
$translated_names = array();
foreach ( $names as $name ) {
$translated_names[] = translate_user_role( $name );
}
return implode( $a['delimiter'], $translated_names );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment