• Hi,
    I am wanting to add a css class to some of the store listings depending on if the user is logged in or not. I am using a javascript function to achieve this:

    if ( is_user_logged_in() ) {
            ?>
            <script type="text/javascript">
                   function addPetrolClass() {
                        var element = document.getElementById("wpsl-stores");
                        element.classList.add("petrol-choice");
                   }
            </script>
            <?php
        }

    I was attempting to do this using the wpsl_store_data filter but its not working – could you advise what filter / hook would be a good place to do this?

    Thanks

Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi there,

    You don’t need to wrap your code inside of a function, if you do that and you don’t explicitly call the function, the code won’t execute.

    Try this snippet instead, you can put it directly in your functions.php file:

    add_action( 'wp_footer', function () { 
    	if ( is_user_logged_in() ) {
            ?>
            <script type="text/javascript">
              var element = document.getElementById("wpsl-stores");
              element.classList.add("petrol-choice");
            </script>
            <?php
        }									  
    ?>
    <?php }, 100 );

    I hope that helps.
    Regards,

    Thread Starter southafricanrob

    (@southafricanrob)

    Thanks – makes sense, much appreciated. What I’m trying to do is conditionally hide or show certain store meta fields. Is there perhaps a better way to do this than just hiding the element with Javascript?

    Well, if you want to to this conditionally based on the user being logged in or not for example, it is way simpler and much more elegant to do it in the wpsl_listing_template filter.

    You can fine-tune what you want your listing template to look like, and you can include conditional code there, like for example this snippet, that will hide the direction URL from the listing template if the user is not logged in:

    if ( is_user_logged_in() ) {
        $listing_template .= "\t\t\t" . '<%= createDirectionUrl() %>' . "\r\n"; 
    }

    I hope that helps.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Where to add Javascript to add a class?’ is closed to new replies.