Skip to content

Instantly share code, notes, and snippets.

@andrewwoods
Created January 7, 2015 18:30
Show Gist options
  • Save andrewwoods/095d4013f976f2026e5a to your computer and use it in GitHub Desktop.
Save andrewwoods/095d4013f976f2026e5a to your computer and use it in GitHub Desktop.
WordPress Widget Boilerplate
<?php
add_action( 'widgets_init', 'register_my_widget' );
class My_Widget extends WP_Widget
{
function __construct() {
$widget_options = array(
'classname' => 'my-widget-class'
,'description' => __('Description of the Widget', 'textdomain')
);
$control_options = array(
'width' => '400px'
);
parent::__construct(
'my-widget-base-id', // Base ID
__( 'Title Of My Widget', 'site' ), // Name
$widget_options,
$control_options
);
}
/**
* Outputs the form on sidebar admin
*
* @param array $instance The widget options
*/
function form( $instance ) {
?>
<p>
Paragraph goes here.
</p>
<div>
<label for="<?php echo $this->get_field_id( 'person_name' ); ?>">Full Name</label>
<input type="text" class="widefat"
id="<?php echo $this->get_field_id( 'person_name' ); ?>"
name="<?php echo $this->get_field_name( 'person_name' ); ?>"
value="<?php echo $instance['person_name']; ?>">
</div>
<div>
<label for="<?php echo $this->get_field_id( 'person_email' ); ?>">Email</label>
<input type="email" class="widefat"
id="<?php echo $this->get_field_id( 'person_email' ); ?>"
name="<?php echo $this->get_field_name( 'person_email' ); ?>"
value="<?php echo $instance['person_email']; ?>">
</div>
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
function update( $new_instance, $old_instance ) {
$instance = array();
$instance['person_name'] = ( ! empty( $new_instance['person_name'] ) ) ? strip_tags( $new_instance['person_name'] ) : $old_instance['person_name'];
$instance['person_email'] = ( ! empty( $new_instance['person_email'] ) ) ? strip_tags( $new_instance['person_email'] ) : $old_instance['person_email'];
return $new_instance;
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
function widget($arg, $instance) {
$widget_title = apply_filters( 'widget_title', $arg['widget_name'] );
echo $arg['before_widget'];
if ( ! empty( $arg['widget_name'] ) ) {
echo $arg['before_title'] . $widget_title . $arg['after_title'];
}
echo __('Full Name:', 'site') . $instance['person_name'] . '<br />';
echo __('Email:', 'site') . $instance['person_email'] . '<br />';
echo $arg['after_widget'];
}
}
function register_my_widget() {
register_widget( 'My_Widget' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment