How to add a class when there’s no sidebar?

I would like to add a class to a page template’s body if the sidebar is not defined. How can I do that?

Related posts

Leave a Reply

4 comments

  1. if you are using an actual page template (as selected in the dropdown panel in the admin area) then using is_page_template(‘file-name.php’) in the body_class function will do it.

    then, the CSS would be body.class-name #content would apply to only that template area.

  2. If you don’t know the names of the sidebars you can use wp_get_sidebars_widgets():

    add_filter( 'body_class', 'wpse_77719_sidebar_body_class' );
    
    function wpse_77719_sidebar_body_class( $classes )
    {
        $classes[] = wp_get_sidebars_widgets() ? 'has-sidebar' : 'no-sidebar';
        return $classes;
    }
    

    If you know the names use is_active_sidebar() in that function like @s_ha_dum suggested.

  3. With php we can have this with ob_start() and ob_get_clean() but it is kinda hacky.

    Better to use javascript:

    if (!document.contains(document.getElementById('secondary'))) {
        document.body.classList.add('no-sidebar');
    }
    

    where secondary is your sidebar ID