If you need to create a simple shortcode to hide part of post content while showing it to logged-in users, here you are:

add_shortcode('protect', function ($attrs, $content) {
  if (is_user_logged_in()) {
    return $content;
  } else {
    return '<p>Only for friends.</p>';
  }
});

You will use it surrounding your to-be-hidden post part with [protect] and [/protect].

Super easy and super effective. Of course, you can install a membership plugin, if you prefer.

To change the shortcode tag, modify the word “protect” in the code above.

User roles

You can even add a condition based on the logged-in user role.

add_shortcode('protect', function ($attrs, $content) {
  if (is_user_logged_in() && current_user_can('editor')) {
    return $content;
  } else {
    return '<p>Only for friends.</p>';
  }
});

The code above is checking the editor role, but you can check capabilities and/or define specific capabilities using the role editor plugin.

Caches

Pay attention to caching plugins: be sure they’re not caching pages when a user is logged in, otherwise, the full content is cached and served to everyone!

Similar Posts

Leave a Reply