Conditionally applying CSS

2 Replies ·

  1. Hi Justin,

    Is it possible to conditionally add a declaration to an existing CSS class in Wordpress ?

    Let say I have the following CSS class :

    .ee-filter-form {
        margin: 0 0 2em 0;
        clear: both;
    }
    

    Then, I would like to do something like this to hide the filter form when the user is not logged in :

    if ( ! is_user_logged_in() ) {
    $class[.ee-filter-form] .= {display:none;} // I know, I know, I am a little simplistic here !!!
    }
    

    Thanks in advance for your help !

    Patrick

  2. Justin Tadlock

    You can’t conditionally execute CSS in your style.css file. But, you could hook it into your header.

    Use the following code in your theme’s functions.php:

    add_action( 'wp_head', 'th_hide_filter_form', 99 );
    
    function th_hide_filter_form() {
    
        if ( ! is_user_logged_in() ) { ?>
    
            <style type='text/css'>.ee-filter-form { display: none; }</style>
        <?php }
    }
    

    Generally speaking, you should probably not show the form at all. If this is from a plugin, it might have a way to filter this form and conditionally show/hide it.

  3. Patrick Sergerie

    Thanks Justin ! Works fine !

    You are right about hooking into the plugin form (it is in fact just a simple dropdown filter form) but unfortunately, as it is (too often) the case in many Wordpress plugin, there is no filter hook to accomplish this. I guess there would be to many combinations to cover everybody’s needs.

    Anyway, again, the day will come that I will be able to code my own event (simple) plugin and will no longer have to find workarounds for accomplish rudimentary tasks.

    Have a good week !

    Patrick