WordPress.org

Ready to get started?Download WordPress

Forums

Filter Widget Defaults: How do I check to see if widget has a title? (2 posts)

  1. Suzanne Ahjira
    Member
    Posted 2 years ago #

    As a designer, I want to "restructure" the widget output a bit to accommodate a design requirement and I know I can do this to some extent by filtering the widget defaults with this filter:

    add_filter('register_sidebar_defaults','alter_widget_output');
    function alter_widget_output( $defaults ) {
    
      $defaults['before_widget'] = '<div id="%1$s" class="widget %2$s"><div class="widget-wrap">';
      $defaults['before_title'] = '<h4 class="widgettitle">';
      $defaults['after_title'] = "</h4>\n";
      $defaults['after_widget'] = "</div>\n</div>\n";
    
      return $defaults;
    
    }

    However, in one case, I need to move the opening tag for the widget-wrap div AFTER the widget title so that the widget title is NOT within the widget-wrap like this:

    function alter_widget_output( $defaults ) {
    
      $defaults['before_widget'] = '<div id="%1$s" class="widget %2$s">';
      $defaults['before_title'] = '<h4 class="widgettitle">';
      $defaults['after_title'] = "</h4>\n<div class="widget-wrap">\n";
      $defaults['after_widget'] = "</div>\n</div>\n";
    
      return $defaults;
    
    }

    The problem with this is that, when you do NOT provide a widget title for any given widget, you also lose the tag that opens the widget-wrap div :-/ Not good.

    So my question is this... is there a template or conditional tag in WP that would allow me to check if a widget title has been specified so I could do something like this?

    function alter_widget_output( $defaults ) {
    
      if($has_title) {
        $defaults['before_widget'] = '<div id="%1$s" class="widget %2$s">';
        $defaults['before_title'] = '<h4 class="widgettitle"><div class="widget-wrap">';
      } else {
        $defaults['before_widget'] = '<div id="%1$s" class="widget %2$s"><div class="widget-wrap">';
        $defaults['before_title'] = '<h4 class="widgettitle">';
      }
      $defaults['after_title'] = "</h4>\n";
      $defaults['after_widget'] = "</div>\n</div>\n";
    
      return $defaults;
    
    }

    Thanks in advance.

  2. bcworkz
    Member
    Posted 2 years ago #

    What you want to do may be possible, but not with the filter you are using. You probably want the filter 'widget_display_callback'. On this filter, I believe the title is in an array of the 1st parameter passed. Dig into widgets.php to get specifics. This is not guaranteed to work because a widget developer could choose to not apply this filter.

    Honestly, this looks like a CSS issue that could be resolved without hacking HTML structure. It's also poor practice to put opening tags in an after_element value, even if it does work.

Topic Closed

This topic has been closed to new replies.

About this Topic