When publishing articles or resources, you may want certain content to be visible only to logged-in users. This 'login to view' feature is simple to implement and highly practical. This guide explains how to achieve it in WordPress.
Core Implementation
Add the following PHP code to your current theme's functions.php file:
// Shortcode function for login-protected content
function login_to_read($atts, $content = null) {
// Set default notice message
$atts = shortcode_atts(
array(
'notice' => 'This content requires <a href="' . wp_login_url() . '" title="Login to view">login</a> to view.'
),
$atts,
'login'
);
// Check if user is logged in, content exists, and not in feed
if (is_user_logged_in() && !is_null($content) && !is_feed()) {
return do_shortcode($content); // Return and parse nested shortcodes
}
// Return the notice message
return $atts['notice'];
}
add_shortcode('login', 'login_to_read');
Code Explanation & Improvements
This version includes several optimizations:
- Enhanced Security: Uses
shortcode_atts()correctly, specifying the shortcode name. - Better Functionality: Uses
wp_login_url()to generate the login link dynamically instead of hardcoding/wp-admin. - Improved Compatibility: Processes nested shortcodes within the hidden content via
do_shortcode(). - Clearer Structure: Correct indentation and added comments.
How to Use
After adding the code, switch your post editor to Text mode (not Visual) and wrap the content you want to hide with the shortcode.
Usage Examples
1. Using the default notice:
[login]This is hidden content visible only to logged-in users.[/login]
2. Using a custom notice:
[login notice="Please <a href="/login">log in</a> to view the full resource."]Important download links or detailed tutorial here.[/login]
Important Notes
- This feature relies on WordPress's user system. Ensure user registration is enabled or you have registered users.
- The shortcode works within post/page content. Using it in sidebars/widgets may require additional handling.
- The notice message can include HTML for styling the login link.