Skip to content

Instantly share code, notes, and snippets.

@maxxscho
Created October 2, 2012 10:13
Show Gist options
  • Save maxxscho/3818007 to your computer and use it in GitHub Desktop.
Save maxxscho/3818007 to your computer and use it in GitHub Desktop.
WORDPRESS: Widget base structure
<?php
class YourClassName extends WP_Widget {
public function YourClassName()
{
// Widget Options
$widget_ops = array(
'classname' => 'yourclassname',
'description' => 'Your description'
);
// Control Options
$control_ops = array(
'width' => 250,
'height' => 350,
'id_base' => 'yourclassname'
);
// Instance Widget
$this->WP_Widget( 'yourclassname', 'Your Widget Name', $widget_ops, $control_ops );
}
/* The form for the backend configuration in the "Widget" Sector of the Wordpress backend
============================================================================ */
public function form( $instance )
{
// Set default arguments
$defaults = array();
// Merging args with defaults
$instance = wp_parse_args( (array) $instance, $defaults );
// Show the form - this is just an example
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>">Title</label>
<input type="text" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" id="<?php echo $this->get_field_id( 'title' ); ?>" class="widefat" />
</p>
<?php
}
/* Save the new configuration
============================================================================ */
public function update( $new_instance, $old_instance )
{
$instance = $old_instance;
$instance['title'] = strip_tags( $new_instance['title']);
// and so on…
return $instance;
}
/* Display the widget
============================================================================ */
public function widget( $args, $instance )
{
extract($args);
$title = apply_filters('widget_title', $instance['title']);
// Start the widget output
echo $before_widget;
// Widget Title
if( ! empty($title) ) { echo $before_title . $title . $after_title; }
// Your widget-content goes here
// Close the widget
echo $after_widget;
}
}
/* Register the new Widget
==================================== */
function load_your_widget() {
register_widget( 'YourClassName' );
}
add_action( 'widgets_init', 'load_your_widget');
//End of file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment