Codepolice

Random posts from Ola in English. Mainly about programming and the web.

Creating a empty/blank text widget for WordPress without additional markup and divs

WordPress provide a simple text widget that you can use on your blog to add some random HTML, Ads, images and so on. But i has one problem and that is that it’s always adding some extra HTML like this.

<div class="widget">
 <div class="textwidget">
 </div>
</div>

Sometimes you really do not want this code if you for example want to add a widget to a ul and want the outer tag to be a li. I tried to Google for this but surprisingly i didn’t find a single “Super Empty Text Widget” so i created one myself.

/**
 * SuperEmptyWidget Class
 */
class SuperEmptyWidget extends WP_Widget {
    /** constructor */
    function SuperEmptyWidget() {
        parent::WP_Widget(false, $name = 'SuperEmptyWidget');
    }
 
    /** @see WP_Widget::widget */
    function widget($args, $instance) {
        extract( $args );
        $content = $instance['content'];
        echo $content;
    }
 
    /** @see WP_Widget::update */
    function update($new_instance, $old_instance) {
	$instance = $old_instance;
	$instance['content'] = $new_instance['content'];
        return $instance;
    }
 
    /** @see WP_Widget::form */
    function form($instance) {
        $content = esc_attr($instance['content']);
        ?&gt;
         &lt;p&gt;
          &lt;label for=&quot;&lt;?php echo $this-&gt;get_field_id('content'); ?&gt;&quot;&gt;&lt;?php _e('Content:'); ?&gt;&lt;/label&gt;
		          &lt;/p&gt;
          &lt;textarea class=&quot;widefat&quot; cols=&quot;20&quot; rows=&quot;16&quot; id=&quot;&lt;?php echo $this-&gt;get_field_id('content'); ?&gt;&quot; name=&quot;&lt;?php echo $this-&gt;get_field_name('content'); ?&gt;&quot;&gt;&lt;?php echo $content; ?&gt;&lt;/textarea&gt;
 
        &lt;?php
    }
 
} // class SuperEmptyWidget
 
// register SuperEmptyWidget widget
add_action('widgets_init', create_function('', 'return register_widget(&quot;SuperEmptyWidget&quot;);'));

Just add that to your functions.php and you should have a widget that do not add any crap either before or after the content.

Leave a Reply