Create private notes and members-only content

Two cool tricks today, how to add content that is only displayed to logged-in members, and how to leave private notes that are displayed only to admins.

Private Notes

When working on posts and pages, drop yourself a private note that only you (and other admins) can see. All you need is the following code in your theme’s functions.php file:

function private_notes($atts, $content = null) {
	if (current_user_can('publish_posts')) {
		return '
' . $content . '
'; } return ''; } add_shortcode('note', 'private_notes');

This function sets up a shortcode that you can use in any post or page. Here is an example of how it works:

[note]
This is a private note that only admins can see :)
[/note]

When displayed, private notes will be wrapped with the following markup:

This is a private note.

Notice the included private-note class, making easier to style. As with most everything else, this method is highly customizable. Explore the code, the Codex, and get jiggy with it.

Members Only Content

Another cool trick is displaying custom content for members and/or visitors only.

Display content only to visitors

To set up a shortcode that displays content only to visitors, add this to your theme’s functions.php file:

function content_for_visitors($atts, $content = null) {
	if ((!is_user_logged_in() && !is_null($content)) || is_feed()) {
		return $content;
	}
	return '';
}
add_shortcode('visitors', 'content_for_visitors');

With that code in place, you can add custom for visitors with a simple shortcode in any post or page, like so:

[visitors]
This content will only be displayed to visitors.
[/visitors]

Display content only to logged-in users

To set up a shortcode to display content only to logged-in users, add the following code to your functions.php file:

function content_for_members($atts, $content = null) {
	if (is_user_logged_in() && !is_null($content) && !is_feed()) {
		return $content;
	}
	return '';
}
add_shortcode('members', 'content_for_members');

With that code in place, you can add custom for members only with a simple shortcode in any post or page, like so:

[members]
This content will only be displayed to members.
[/members]

Customization for these methods is encouraged — have fun!

About

Jeff Starr likes to build websites, write books, and open presents on Christmas!

3 thoughts on “Create private notes and members-only content

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>