Home > Net >  Woocommerce - hide an element if logged in, show element if logged out
Woocommerce - hide an element if logged in, show element if logged out

Time:04-07

i've found the following code to make an element change to display:block; if a user is logged in

.logged-in .price{
 display: none;
 }

and also

<?php if ( is_user_logged_in() ) {
echo '<style>p.price {display:none;}</style>';
} else {
echo '<style>p.price {display:block;}</style>';
}
?>

but neither seems to work properly. it will hide the element, but if i log out, the element is still hidden. does anyone have an answer? thankyou :)

CodePudding user response:

The body tag will have a logged-in class when the user is logged in. So using the following will work.

body.logged-in .price {
    display: none !important;
}

If you want to remove the !important attribute then you would need to target more specifically which .price element you wish to remove due to Woocommerce being very specific with it's css selectors.

Also to note, you can add a :not() modified to the body selector if you wish to do the reverse, i.e...

body:not(.logged-in) .price {
   // do something...
}

CodePudding user response:

Try following code that worked fine for me.



    function example_function()
    {
       if ( is_user_logged_in() ) 
       {
          echo 'p.price { display: none; }';
   }
}
add_action('init', 'example_function');

  • Related