Limit Content For Logged Out Users

This code enables you to limit the content on single posts & pages to logged out users.

You can limit the content simply by using a character limit in the code.

The full content will only be displayed for logged in users.

And a login form will display after the content limit for logged out users on single posts and pages only.

The code is very flexible and enables you to easily modify the conditional tags and character limit. You can also use the code for custom post types.

Here’s an example of what logged out users see:

logged-out-users

And here’s what logged in users see:

logged-in-users

Simply as that. All you need to do is copy & paste the PHP code to the end of your child themes functions file and change the styling of your login form if desired.

The code works in any theme as it uses a WordPress hook and has been tested using the Genesis Sample child theme by StudioPress.

The solution in this tutorial is based on this question from a members of the StudioPress Community Forums:

Hi, Just setting up a new blog and we want to display the header and either the first couple of line of each blog or an excerpt to all users but only display the full articles to logged in users.

Here’s the code for logged in members:

add_filter( 'the_content', 'filter_content', 10, 1 ); 
 
function filter_content( $content ) { 
    
    $limit = wp_trim_words( get_the_content(), 40, '.....' );

    $login_form = sprintf( '<p><h4 class="entry-meta"><a href="%s">Register</a> or login below to view all content.</h4></p>', esc_url( wp_registration_url() ) );
    
    $login_form .= sprintf( '<p class="login-form">%s</p>', wp_login_form( array( 'echo' => false ) ) );
    
    $limit = $limit . $login_form;

    $output = ! is_user_logged_in() && is_single() ? $limit : $content;
    
    return $output;
}

You could also swap out is_single() and use is_singular(array( 'post','page' ) ) instead.

Related Code Snippets

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.