Skip to content

Instantly share code, notes, and snippets.

@annalinneajohansson
Created October 29, 2015 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save annalinneajohansson/5db51cb4ae88063a5b0b to your computer and use it in GitHub Desktop.
Save annalinneajohansson/5db51cb4ae88063a5b0b to your computer and use it in GitHub Desktop.
Base for WP_Widget
<?php
class My_Widget extends WP_Widget {
public function __construct() {
$widget_ops = array(
'classname' => 'my-widget',
'description' => __( 'My Widget description', 'textdomain' ),
);
$this->WP_Widget( 'My_Widget', __( 'My Widget title', 'textdomain' ), $widget_ops );
}
public function widget( $args, $instance ) {
extract( $args, EXTR_SKIP );
$title = empty( $instance['title'] ) ? false : apply_filters( 'widget_title', $instance['title'] );
$text = empty( $instance['text'] ) ? false : $instance['text'];
echo $before_widget;
if ( $title ) {
echo $before_title . $title . $after_title;
}
if ( $text ) {
echo $before_text . wpautop( $text ) . $after_text;
}
echo $after_widget;
}
public function form( $instance ) {
$instance = wp_parse_args(
(array) $instance,
array(
'title' => '',
'text' => '',
)
);
$title = $instance['title'];
$text = $instance['text'];
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title' ); ?>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>"
name="<?php echo $this->get_field_name( 'title' ); ?>" type="text"
value="<?php echo attribute_escape( $title ); ?>" />
</label>
</p>
<p>
<label for="<?php echo $this->get_field_id( 'text' ); ?>"><?php _e( 'Text' ); ?>
<textarea class="widefat" id="<?php echo $this->get_field_id( 'text' ); ?>" name="<?php echo $this->get_field_name( 'text' ); ?>"><?php echo attribute_escape( $text ); ?></textarea>
</label>
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
foreach ( $new_instance as $key => $value ) {
switch ( $key ) {
default:
$instance[ $key ] = $new_instance[ $key ];
break;
}
}
return $instance;
}
}
@punit5658
Copy link

Hi, $this->WP_Widget() is deprecated so use parent::__construct() instead of $this->WP_Widget().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment