A shortcode to display content only if the user is logged in to WordPress

Why

  • You want to show content only to a signed in user.

Usage

[logged_in]This content is visible only to logged-in users.[/logged_in]

Shortcode

The following is the source code of the logged_in shortcode for displaying content only if the current user is logged in. Lines beginning with a # character are comments that get ignored by WordPress. We provide comments in detail so you can fully understand what is going on. You can delete these comments once you understand what the code is doing. To install this shortcode, see below.

# logged_in shortcode
#
# Purpose
#
# A WordPress shortcode that displays content only if the
# current user is logged into the website. Otherwise
# nothing is displayed.
#
# Usage
#
#   [logged_in]This is shown only to logged in users[/logged_in]
#
function logged_in_shortcode($atts, $content = null) {
    #
    # Check whether the current user is logged into the
    # website by calling the built-in is_user_logged_in
    # function. This function returns true if the user
    # is logged into the site, or false otherwise.
    #
    if (is_user_logged_in()) {
        #
        # The user is logged in. The do_shortcode function
        # will process any shortcodes that are in the content.
        #       
        return do_shortcode($content);
    } else {
        #
        # The user is not logged in. Return a blank string.
        #
        return '';
    }
}

#
# Once the function is defined, it needs to be registered
# with WordPress as a shortcode. This is done with the
# add_shortcode function, which takes two parameters: the
# tag name, e.g., logged_in, and the function to execute
# when the shortcode is encountered in a post. See:
# https://developer.wordpress.org/reference/functions/add_shortcode/
#
add_shortcode('logged_in', 'logged_in_shortcode');

References

Design decisions

  • We used the name “logged_in” rather than “signed_in” as “logged in” is more commonly used in WordPress documentation. We favor being consistent with the standard documentation.
  • We used the name “logged_in” instead of “loggedin” to be consistent with other WordPress functions such as is_user_logged_in().

How to use

To manually install this shortcode, you can add it to functions.php in your theme. However, this is dangerous and we recommend using a plugin that allows you to create and manage custom bits of code without changing your theme files. Two plugins we recommend are Code Snippets and WPCode. Both have free versions that allow you to create custom shortcodes.

Leave a Reply