So I’m trying to create a code (in functions.php) that displays a widget content, from shortcode, based on whether the user is logged in or logged out (visitor). I am successful in displaying content for logged in users, but not for visitors, as I need everything to happen in the same widget. The approach I’m trying is by using two different shortcodes, like this:
[member_only]You are logged in.[/member_only] [visitor_only]Login / Register[/visitor_only]
If user is logged in, it displays the content of
[member_only]You are logged in.[/member_only]
If user is logged out, it displays the content of
[visitor_only]Login / Register[/visitor_only]
My code:
/* BEGIN LOGIN BUTTON WIDGET 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');
function visitor_only_shortcode($atts, $content = null)
{
if (is_user_logged_in() && !is_null($content) && !is_feed()) {
return "";
}
else {
return $content; }
}
add_shortcode('visitor_only', 'visitor_only_shortcode');
/* END LOGIN BUTTON WIDGET SHORTCODE */
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The code exactly as you put it in your question works fine for me and does exactly what you suggested.
To make it work I had to make sure my WP post editor was in code editor mode as HTML or Visual Editor may create extra problems:
And this is what my test code in the post editor looked like, when I had a successful test:
<!-- wp:html --> <p>this is the content</p> <p>more content [member_only]You are logged in.[/member_only] [visitor_only]Login / Register[/visitor_only] </p> <!-- /wp:html -->
You can make the second shortcode a bit clearer to read by adding ! for ‘not’ on the front of the first condition, then the structure is the same as the first shortcode, and you don’t need the else:
function visitor_only_shortcode($atts, $content = null)
{
if (!is_user_logged_in() && !is_null($content) && !is_feed()) {
return $content;
}
}
add_shortcode('visitor_only', 'visitor_only_shortcode');
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0
