WordPress Snippets at WPcustoms

Restrict content to logged in users shortcode

This function creates a shortcode [member] which limits access on your site. Content wrapped in that shortcode is only visible for logged in users. Everybody else gets a message that this content is limited for logged in users. Pretty cool if you want to encourage your signup ratio and build a community where people regularly log in to your site.


/**
 * Snippet Name: Restrict content to logged in users shortcode
 * Snippet URL: https://wpcustoms.net/snippets/restrict-content-to-logged-in-users-shortcode/
 */
  // usage: [member] only logged in users can see this text[/member]
function wpc_restrict_content( $atts, $content = null ) {
    if ( is_user_logged_in() && 
        !is_null($content) && 
        !is_feed() 
         ) {
            
        return $content;
    } else {
        
        return __( 'Sorry, this content is only available for logged users.', 'yourtheme' );
    }
}
add_shortcode( 'member', 'wpc_restrict_content' );