How to add shortcode to display content only for logged-in users

Posted on: July 5th, 2022
By: Tadeo Martinez

You can easily add the code only to show text to logged-in users in the PHP template, but what if you want to do it on a page through the editor?

Add the below code to your functions.php to be able to use the shortcode.

function member_only_shortcode($atts, $content = null)
    if (is_user_logged_in() && !is_null($content) && !is_feed()) {
        return $content;
add_shortcode('member_only', 'member_only_shortcode');

Use the shortcode below.

[member_only]User is logged in.[/member_only]

To do this functionality in the PHP template, you use the following code:


if ( is_user_logged_in() ) {
    echo 'Welcome, registered user!';
} else {
    echo 'Welcome, visitor!';

I found these snippets from this support article.

Have any questions or comments? Write them below!

Leave a Reply

Your email address will not be published. Required fields are marked *