0

I'm trying to add a login/register button to my home page only when a user is logged out. I've tried using the do_shortcode call into the relevant template: (I know there is currently no conditional to check if logged in but I just want to ensure that the shortcode actually works first of all)

add_shortcode('loginout_button','add_loginout_button');

function add_loginout_button {
$content = '<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">
                LOGIN/REGISTER
                </a>  
                </div>';
return $content; 
}

which is then called using the

echo do_shortcode('[loginout_button']);

in the template, but the shortcode is not registering- it's only echoing [loginout_button]. I guess this is not the way to do it then! Do I have to use a filter and then apply_filters? It made sense in my head but I honestly now need some help with this one- thanks in advance!

0

First of all, your shortcode usage code is incorrect, correct code is:

echo do_shortcode('[loginout_button]');

Now, if you want to echo the login/logout button only when user is not logged in, you can use the function is_user_logged_in(). There are two ways to do this

1). Conditional logic inside your shortcode.

add_shortcode('loginout_button','add_loginout_button');
function add_loginout_button() {
    if ( is_user_logged_in() ) {
        return '<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">LOGIN/REGISTER</a></div>';
    }
    return false;
}

This is the recommended way because you can use the shortcode anywhere and get the expected result.

2) Wrap your shortcode usage code in the conditional tag

if ( is_user_logged_in() ) {
    echo do_shortcode('[loginout_button]');
}
0

Did you copy/paste right your code?

It's missing the parenthesis on add_loginout_button. It should be:

function add_loginout_button() {
$content = '<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">
                LOGIN/REGISTER
                </a>  
                </div>';
return $content; 
}

This should be added on functions.php.

And you can also check if a user is logged in or not with is_user_logged_in():

add_shortcode('loginout_button','add_loginout_button');

function add_loginout_button() {
    if( is_user_logged_in() ) {
        $content = '<div style="text-align:center;background-color:#7114B7;padding:15px;border-radius:50px;margin:20px;"><a href="">LOGIN/REGISTER</a></div>';
    } else {
        $content = '';
    }

    return $content; 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.