Question

I have a sidebar in WooCommerce showing sub categories with the "Product categories" widget. However when a category has no subcategories I wan't the sidebar to be hidden.

is_active_sidebar is only checking if the sidebar has widgets and not if the current page you're on has widget content. Therefor the sidebar is still shown, because it does contain a widget, but there are no content to be shown on a category without sub categories.

How can I check if any of the sidebar widgets have content on the current page, so that I can use that conditional to hide the sidebar, if there is no content to be shown?

Was it helpful?

Solution

Could the is_active_widget function dynamically check each widget added to the sidebar if they have content and return true if any of them have?

No, it couldn't. You could check if any widgets have saved data on them, but whether a widget has saved data is not a good indication of whether or not it has anything to render. The only way this approach would work is if you personally inspected every single possible widget and made note of which values would result in the widget rendering anything.

The closest you could get is to capture the output of dynamic_sidebar() with output buffering and then check if it has any HTML in it before outputting anything:

<?php
ob_start();

dynamic_sidebar( 'sidebar' );

$sidebar = ob_get_clean();

if ( $sidebar ) :
    ?>

    <aside class="sidebar">
        <?php echo $sidebar; ?>
    </aside>

    <?php
endif;
?>

The problem with this is that some widgets could still output HTML, even if there's no content visible to the user. In that case the sidebar would still be rendered. It might be possible to work around some cases by using strip_tags to remove any HTML before checking if the sidebar is empty:

if ( trim( strip_tags( $sidebar ) ) ) :

endif;
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top