1

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?

  • It depends on the approach each widget is developed. But "Product categories" is not a WordPress widget, so the question is off-topic. – Max Yudin Aug 9 '18 at 8:14
  • Yes you have to tweak the wordpress widget instead of sidebar – Latheesh V M Villa Aug 9 '18 at 8:16
  • "Product categories" was just to give a realistic example of where the sidebar could actually be completely empty. I wan't this to work with any widget. 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? is_active_widget function – Skovsgaard Aug 9 '18 at 8:31
2

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;
  • I just tested this and it works as expected - at least with the core widgets I'm using at the moment. Thanks for providing an insightful answer. – Skovsgaard Aug 9 '18 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.