WordPress Shortcode: “Show If” for conditional content display

Here’s the code for a simple WordPress shortcode to conditionally display content within pages based on supplied usernames or roles.

 

Example Usage

Display to a specified user:


Display to a specified role:


Display to both a user and a role:


Display to multiple roles (comma separated list. “username” works the same):


 

Code

It’s in a GitHub gist at https://gist.github.com/vylesk/64ca3e6d3da77fb853ca7af181165e6b and below:

<?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));
}
?>

Developing WordPress: What You Need to Learn

  • Download and install WordPress on a development PC.
    • LAMP/WAMP/XAMP stack (Apache, MySQL, PHP)
    • Database table naming. Default is “wp_”. Change the name in config.php so multiple installations in the one DB.
  • Training:
  • Official WordPress sites:
  • Terms and Concepts (and how they work)
    • Users
    • Roles
    • Taxonomies
    • Posts (this the core of WordPress) and Post Types
    • Custom Post Types
    • Database structure
  • Custom Development
    • Themes
    • Plug-ins
    • Shortcodes
    • Page Templates
    • ‘Meta’ fields
    • Custom Roles
    • Extending user information/fields
    • WordPress API
    • Actions, Hooks, Filters
  • Achieving specific ends
    • Creating forms for users in the front-end
  • Good Themes and plug-ins to know
    • Themeco ‘X’ or ‘Pro’ themes
    • Advanced Custom Fields (ACF)
  • Other things to think about
    • Form validation for custom forms
    • Data sanitisation
    • Security
    • Exception handling (500 & 404)
    • Unit test and general testing
      • https://codex.wordpress.org/Theme_Unit_Test
    • Logging
    • User analytics (tracking user behaviour)
    • Different plug-ins (and theme) loading the same javascript resources (e.g. jQuery). Think about version conflicts.
    • Updating themes and plug-ins
    • Debugging (e.g. debug(‘WP_DEBUG’, true);)

Thinking about DevOps:

  • The database stores a lot of configuration data.
  • Plug-in development
  • Theme development
  • Creating dev/test environments from prod.
    • Renaming domains in the .database
  • Can we push dev/test (including config via DB) to prod? Investigate.
  • Deploying themes and plug-ins (is built-in WP the best, even for us?)

Look at:

wordpress.org/extend/plugins/monster-widget/
../theme-check/
../developer/
../debogger/
../log-deprecated-notices/

http://wptest.io/

WordPress Themes & Plugins

Themes

‘X’ Theme or ‘Pro’ Theme
Themeco
https://theme.co/x/
US$55

Divi
Elegant Themes
https://www.elegantthemes.com/
US$89

General

Jetpack
https://jetpack.com/
US$39/99/299/year
– Themes
– Backups
– Monitoring

 

Canonical

Yoast SEO
Free/US$89/year

https://wordpress.org/plugins/tags/canonical/

 

Forms

Contact Form 7
https://contactform7.com/
Free
Comes with X Theme

Gravity Forms
http://www.gravityforms.com/
US$39

Ninja Forms
https://ninjaforms.com/
US$99 (Personal)

 

Security

WordFence
https://www.wordfence.com/
Free or US$99/year

 

Favicon

Built-in with WordPress

Favicon by RealFaviconGenerator
https://wordpress.org/plugins/favicon-by-realfavicongenerator/
Free

 

Schema, Rich Snippets & Social Sharing

  • Schema.org
  • Twitter Cards
  • Open Graph Protocol
  • Microformats

https://wordpress.org/plugins/schema/
https://wordpress.org/plugins/all-in-one-schemaorg-rich-snippets/

Social Sharing
http://www.wpbeginner.com/plugins/best-social-media-plugins-for-wordpress/
https://wordpress.org/plugins/ultimate-social-media-icons/
https://wordpress.org/plugins/ultimate-social-media-plus/

Google Maps

 

e-Commerce

http://www.wpbeginner.com/plugins/best-wordpress-ecommerce-plugins-compared/

WooCommerce
Free

 

Galleries, Sliders and Carousels

Envira Gallery (with X theme)
http://enviragallery.com/
UD$29 (Basic)

Soliloquy (with X theme)
http://soliloquywp.com/
UD$19 (Personal)

 

Spam and Comments

(TBC)

 

Backups, DR, & Monitoring

VaultPress (with JetPack)

BackupBuddy
https://ithemes.com/purchase/backupbuddy/
US$80/year

Uptime

 

Site Usage, Analytics, and Mapping

Sitemap
SEO plug-ins

Google XML Sitemaps
https://en-au.wordpress.org/plugins/google-sitemap-generator/

Google Sitemap by BestWebSoft
https://wordpress.org/plugins/google-sitemap-plugin/

Google Analytics
X Theme

MonsterInsights [for full dashboard]
https://wordpress.org/plugins/google-analytics-for-wordpress/
US$39/year

Robots.txt
(TBC)

Meta and keyword tags (per page)
Yoast SEO

 

SEO

Yoast SEO
https://en-au.wordpress.org/plugins/wordpress-seo/
Free or US$89/year

All in One SEO Pack
https://wordpress.org/plugins/all-in-one-seo-pack/
US$136/year

 

SSL

Migrate or Change website domain
https://wordpress.org/plugins/tags/migrate/
https://wordpress.org/plugins/duplicator/
https://wordpress.org/plugins/all-in-one-wp-migration/

 

Email and Contact Lists

MailChimp
https://mailchimp.com/

https://mc4wp.com/ (MailChimp plug-in)

 

Membership & Subscription

https://wordpress.org/plugins/wp-members/
Untested

 

Active Directory Integration