Categories
Code

WordPress Protect Content shortcode

The simplest way to hide content from logged out users by wrapping content in [protect] hide me [/protect]

/*************
PROTECT SHORTCODE - If user is not logged in, content within [protect] is replaced with a predefined string.
*****************/

add_action( 'init', 'dm2_register_protect_shortcode');

function dm2_register_protect_shortcode() {
   add_shortcode('protect', 'dm2_protect_function');
}

function dm2_protect_function($atts, $content = null) {

     if ( is_user_logged_in() ) {
          $return_string = $content;
     } else {
          $return_string = 'You must be logged in to view this content';
     }

     wp_reset_query();
     return $return_string;
}