Shortcode that hides content from non-logged in Users

By using the shortcode in this way you can hide everything between the shortcode’s beginning, and its end.

[loggedin_only]
This content is only visible to logged-in users, though we haven’t activated on dev.gooloo.de, so you can actually see it.
[/loggedin_only]

To use this, add the following PHP Snippet to your WordPress’ functions.php or via a Code Snippets Plugin.

function loggedin_only_shortcode($atts, $content = null) {
    if (is_user_logged_in()) {
        return do_shortcode($content);
    } else {
        $current_url = urlencode(get_permalink());
        $login_url = wp_login_url($current_url);
        $register_url = wp_registration_url();
        
        return 'You can only see this content, when you are logged in. Please <a href="' . $register_url . '">sign up</a> or <a href="' . $login_url . '">sign in</a>, to view this content.';
    }
}
add_shortcode('loggedin_only', 'loggedin_only_shortcode');

Posted

in

by

Tags:

Comments

Leave a Reply

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