WP-Mix

A fresh mix of code snippets and tutorials

WordPress shortcodes for private content

I use these snippets all the time, so I’m posting them here at WP-Mix for easy access. The first shortcode can be used to display content only to logged-in users (based on capability). And the second shortcode can be used to display content only to visitors (non-logged-in users).

Display content to logged-in user based on role

Add this to your plugin or theme functions.php file:

/* 
	shortcode: show content only to logged-in users (based on capability)
	syntax: [user_access cap="read" deny="Log in to view this content"]Lorem ipsum dolor sit amet[/user_access]
	see @ https://codex.wordpress.org/Roles_and_Capabilities#Capabilities
*/
function user_access($attr, $content = null) {
	extract(shortcode_atts(array(
		'cap'  => 'read',
		'deny' => '',
	), $attr));
	if (current_user_can($cap) && !is_null($content) && !is_feed()) return $content;
	return $deny;
}
add_shortcode('user_access', 'user_access');

This shortcode [user_access] accepts two attributes, one for the capability and another for the message that is displayed if the content is not displayed. Check the code comments for more infos.

Display content only to non-logged in visitors

Add this to your plugin or theme functions.php file:

/* 
	shortcode: show content only to visitors
	syntax: [visitor_access deny="Log out to view this content"]Lorem ipsum dolor sit amet[/visitor_access]
	see @ https://codex.wordpress.org/Roles_and_Capabilities#Capabilities
*/
function visitor_access($attr, $content = null) {
	extract(shortcode_atts(array(
		'deny' => '',
	), $attr));
	if ((!is_user_logged_in() && !is_null($content)) || is_feed()) return $content;
	return $deny;
}
add_shortcode('visitor_access', 'visitor_access');

This shortcode [visitor_access] accepts one attribute for the message that is displayed if the content is not displayed. Check the code comments for more infos.

Note: it is best practice to namespace your functions.. so for either of these functions you would want to change the function name to something more specific, in order to avoid name-space conflicts with other functions. For example, you would change visitor_access to something like my_custom_prefix_visitor_access, and then also replace the function name in the add_shortcode function.

Related Posts

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress