Skip to content

Instantly share code, notes, and snippets.

@vylesk
Last active August 16, 2019 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vylesk/64ca3e6d3da77fb853ca7af181165e6b to your computer and use it in GitHub Desktop.
Save vylesk/64ca3e6d3da77fb853ca7af181165e6b to your computer and use it in GitHub Desktop.
WordPress Shortcode: "Show If" for conditional content display
<?php
/**
* Plugin Name: "Show If" Shortcode
* Plugin URI: https://jsnelders.com/
* Description: Shortcode to conditionally display content if the user is in a specified role or has a specified username.
* Author: Jason Snelders
* Author URI: http://jsnelders.com
* Version: 190529.1
**/
namespace JasonSnelders\Shortcodes;
/*
* Show the content only if the current user is one of the specified username(s) or in one ofthe role(s).
*
* Attributes:
* role: comma separated list of allowed roles to view the content.
* username: comma separated list of allowed usernames to view the content.
*
* Attrubtes combine as an OR expressess - content is displayed if they user is in the "role" list OR the "username" list.
*/
add_shortcode('show_if', 'JasonSnelders\Shortcodes\show_if_handler');
function show_if_handler($atts = [], $content = null)
{
// Get supplied shortcode attributes.
$show_if_role = "";
$show_if_username = "";
if(isset($atts["role"])) $show_if_role = $atts["role"];
if(isset($atts["username"])) $show_if_username = $atts["username"];
$show_if_role = explode(',', $show_if_role);
$show_if_username = explode(',', $show_if_username);
// Get the current user.
$wp_user = \wp_get_current_user();
$wp_user_roles = $wp_user->roles;
$wp_user_username = $wp_user->user_login;
// Check if current user can view content/
$show_to_user = false;
foreach ($wp_user_roles as $role_slug)
{
if ($role_slug != "" && in_array_case_insensitive($atts, $role_slug))
{
$show_to_user = true;
break;
}
}
if ($show_to_user == false)
{
foreach ($show_if_username as $show_username)
{
if ($show_username != "" && strtolower($show_username) == strtolower($wp_user_username))
{
$show_to_user = true;
break;
}
}
}
ob_start();
if ($show_to_user == true)
{
// Show the content
$content = do_shortcode($content);
echo $content;
}
else
{
// Hide the content
echo "";
}
return ob_get_clean();
}
/*
* Case-insensitive check if a value is in the array.
* (Source: https://gist.github.com/sepehr/6351397)
*/
function in_array_case_insensitive($array, $check_value)
{
return in_array(strtolower($check_value), array_map('strtolower', $array));
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment