Skip to content

Instantly share code, notes, and snippets.

@aurooba
Last active October 17, 2018 17:32
Show Gist options
  • Save aurooba/b80fd9140a232c0c41e548b00db5ce04 to your computer and use it in GitHub Desktop.
Save aurooba/b80fd9140a232c0c41e548b00db5ce04 to your computer and use it in GitHub Desktop.
Shortcode for restricting things based on ANY WordPress role
<?php
/**
* Creates a shortcode [wo_is_role] that allows you to restrict anything inside to a particular role or roles.
* To use: [wo_is_role role="subscriber"] Put content here to show subscriber [/wo_is_role]
* To use with multiple roles: [wo_is_role role="contributor,subscriber"] Put content here to show contributors and susbcribers. [/wo_is_role]
*
* Works with ANY role, including all custom roles.
*/
add_shortcode( 'wo_is_role', 'wo_role_based_permission' );
function wo_role_based_permission( $atts, $content = null ) {
extract( shortcode_atts( array(
'role' => '',
), $atts, 'wo_is_role' ) );
$cuser = wp_get_current_user();
$user_role = $cuser->roles;
$roles_allowed = explode(",", $role);
if ( in_array( $user_role[0], (array) $roles_allowed ) ) {
// you can add in what you want here. In this case, this let's you add in any content and other shortcodes inside that will only be shown to the allowed roles.
return do_shortcode( $content );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment