Skip to content

Instantly share code, notes, and snippets.

@melissacabral
Last active January 20, 2016 16:35
Show Gist options
  • Save melissacabral/0680da2112157212aba3 to your computer and use it in GitHub Desktop.
Save melissacabral/0680da2112157212aba3 to your computer and use it in GitHub Desktop.
Widget API - Basic Setup. Use in a plugin or functions file
<?php
function rad_register_widget(){
register_widget('Rad_Simple_Widget');
}
add_action('widgets_init', 'rad_register_widget');
//our new widget is a copy of the WP_Widget object class
class Rad_Simple_Widget extends WP_Widget{
function __construct(){
$widget_ops = array(
'class_name' => 'rad_widget',
'description' => 'My Widget is Pretty Radical',
);
parent::__construct( 'rad_widget', 'Rad Widget', $widget_ops );
}
//REQUIRED. front-end display. always use 'widget($args, $instance)' function
function widget( $args, $instance ){
//extract the args so we can use them.
//args contains all the settings from the dynamic sidebar
extract($args);
//create the filter hook for the title
$title = apply_filters( 'widget-title', $instance['title'] );
//widget output begins here
echo $before_widget;
if( $title ){
echo $before_title . $title . $after_title;
}
echo 'This is the "meat" of the widget';
echo $after_widget;
//end widget display
}
//REQUIRED. handle saving data. Always use "update($new_instance, $old_instance)"
function update( $new_instance, $old_instance ){
$instance = $old_instance;
//santitize all fields here:
$instance['title'] = wp_filter_nohtml_kses($new_instance['title']);
return $instance;
}
//OPTIONAL. Admin panel form display and defaults. always use "form($instance)"
function form( $instance ){
//set up defaults for each field
$defaults = array(
'title' => 'Simple!'
);
//merge defaults with the user-provided values
$instance = wp_parse_args( (array) $instance, $defaults );
//Form HTML - leave off the form tag and button
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">Title</label>
<input type="text" name="<?php echo $this->get_field_name('title'); ?>" id="<?php echo $this->get_field_id('title'); ?>" value="<?php echo $instance['title']; ?>" />
</p>
<?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment