WordPress Snippet: Member only content shortcode

The following WordPress snippet will allow you to show content inside the shortcode to logged in users only. People who are not logged in will be shown a login form.

Start with the below WordPress snippet.

NOTE: To insert the snippet into your WordPress site, we recommend using the Code Snippets plugin instead of modifying your functions.php file.

// Snippet from NibbleGuru.com
function member_only_func( $atts, $content = null ) {
    // Make sure the content is not null or empty
    // else we do not do anything as there is no content to protect.
    if(!is_null($content) && trim($content) != "") {
        // Make sure user is logged in and is not viewing the feed
        // else we print the login form
        if (is_user_logged_in() && !is_feed()) {
            return $content;
        }
        else {
            $redirect_after_login = get_permalink();
            $login_form = wp_login_form(array('echo' => false, 'redirect' => $redirect_after_login));
            return $login_form;
        }
    }
    else {
        return "";
    }
}

// Hook the shortcode
add_shortcode('member_only', 'member_only_func');

To use the shortcode just use [member_only] tag like following snippet in any post or page:

[member_only] This content will only will seen by members. Other people will see login form instead of this text. Replace this text with text of your choice. [/member_only]

 

Be the first to comment

Leave a Reply