• Resolved andrejcremoznik

    (@andrejcremoznik)


    1. I’ve created a custom widget.
    2. This widget is applied to a sidebar area that is active on multiple templates e.g. the archives and singles.
    3. I would like to display the widget only if is_single() == true.

    There are multiple ways to go about doing that. I could register a new sidebar which would only display on single pages.

    What I’d rather do, however, is somehow check the is_single() condition inside the custom widget class. Checking inside the widget() method does hide the content but the is_active_sidebar() still returns true, because it’s not aware of the hidden widget’s content.

    What is the most appropriate way to handle this?

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • Have you tried using the “is_active_sidebar” as a filter? It provides the sidebar index. With some effort you could get the widgets of the sidebar. If it only contains your widget, and is_single() is false, you could return false.

    Quite a lengthy process though.

    If you are working with a theme, you can prevent your sidebar from being displayed if you buffer “dynamic_sidebar()“, then check the contents. Then you can check if any widgets actually rendered some HTML.

    I use this:

    if ( is_dynamic_sidebar( $sidebar ) ) {
    
      ob_start();
      dynamic_sidebar( $sidebar );
      $sidebar_html = ob_get_clean();
    
      if ( $sidebar_html ) {
        ?>
        <ul id="sidebar" class="sidebar-list">
          <?php echo $sidebar_html ?>
        </ul>
        <!-- /#sidebar -->
        <?php
      }
    
    }
    Thread Starter andrejcremoznik

    (@andrejcremoznik)

    Thanks, even though in the end it’s still a hacky solution. Was hoping for something more proper.

    I’ll opt for a single template only sidebar as I’m developing a complete website and am in control of the template.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Conditionally show custom widget in frontend sidebar’ is closed to new replies.