skip to Main Content

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 🙂

3

Answers


  1. Chosen as BEST ANSWER

    Thanks for this. The addition I forgot to mention was to have the element to stay hidden until clicked again - which is a localStorage thing.

    Final code is below:

    <input type="checkbox" class="tradePriceToggle"> Hide Trade Price
    
    <script>
       $(function() {
       var status = localStorage.getItem('chkStatus');
         if(status == 'true'){
         $("span.price").css("display", "none");
         $(".tradePriceToggle").attr('checked', true)
       }
       else {
            $("span.price").css("display", "block");
            $(".tradePriceToggle").attr('checked', false)
      }
      $(".tradePriceToggle").click(function() {
    if (this.checked) {
      $("span.price").hide();
    }
    else {
      $("span.price").show();
    }
    localStorage.setItem("chkStatus", this.checked);
    });
    });
    </script>
    

  2. 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...
    }
    
    Login or Signup to reply.
  3. Try following code that worked fine for me.

    function example_function() {
      if (is_user_logged_in()) {
        echo '<style>p.price { display: none; }</style>';
      }
    }
    add_action('init', 'example_function');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search