Support » Fixing WordPress » How to use the is_active_sidebar hook from within a widget class?

  • Hello,

    I have a custom widget in a theme that in some cases (conditionally) returns false in its widget() method, i.e. no HTML output.

    The widget area is checked with is_active_sidebar() (the function) before displaying the widgets and wrapping HTML.

    Now, if there is a widget that outputs nothing, is_active_sidebar() is still TRUE because there IS a widget in the sidebar and the wrapping HTML is displayed (an empty aside for example).

    I have a hacky solution with output buffering the widget area and checking if the string is empty.

    As of WordPress 3.9. I found there is a new hook is_active_sidebar (not the function) to manipulate is_active_sidebar() (the function). I would like to use this in the custom widget’s widget() method to set is_active_sidebar to FALSE when the widget returns false / outputs nothing, like the following, but it doesn’t work. How would I go about it?

    function widget( $args, $instance ) {
            extract( $args );
    
            if ( $custom_condition ) {
                add_filter( 'is_active_sidebar', '__return_false');
                return false;
            }
    
            [...]
    
            /* Output widget HTML. */
            echo $output;
        }
  • The topic ‘How to use the is_active_sidebar hook from within a widget class?’ is closed to new replies.