Skip to content

Instantly share code, notes, and snippets.

@justinwhall
Created March 16, 2012 16:46
Show Gist options
  • Save justinwhall/2051050 to your computer and use it in GitHub Desktop.
Save justinwhall/2051050 to your computer and use it in GitHub Desktop.
PHP: WordPress | register basic widget
add_action( 'widgets_init', 'example_load_widgets' );
/**
* Register our widget.
* 'Example_Widget' is the widget class used below.
*
* @since 0.1
*/
function example_load_widgets() {
register_widget( 'Example_Widget' );
}
/**
* Example Widget class.
* This class handles everything that needs to be handled with the widget:
* the settings, form, display, and update. Nice!
*
* @since 0.1
*/
class Example_Widget extends WP_Widget {
/**
* Widget setup.
*/
function Example_Widget() {
/* Widget settings. */
$widget_ops = array( 'classname' => 'sidebar-menu', 'description' => __('Displays a menu in the side bar of "Review Us", "Welcome Packet" and "Patient Forms".', 'example') );
/* Widget control settings. */
$control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );
/* Create the widget. */
$this->WP_Widget( 'example-widget', __('Dental Health Sidebar Menu', 'example'), $widget_ops, $control_ops );
}
/**
* How to display the widget on the screen.
*/
function widget( $args, $instance ) {
extract( $args );
/* Our variables from the widget settings. */
//$title = apply_filters('widget_title', $instance['title'] );
$review = $instance['review'];
/* Before widget (defined by themes). */
echo $before_widget;
/* Display name from widget settings if one was input. */
if ( $review )
printf( '<a href="%1$s">Review us</a>', $review );
/* After widget (defined by themes). */
echo $after_widget;
}
/**
* Update the widget settings.
*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
/* Strip tags for title and name to remove HTML (important for text inputs). */
$instance['review'] = strip_tags( $new_instance['review'] );
return $instance;
}
/**
* Displays the widget settings controls on the widget panel.
* Make use of the get_field_id() and get_field_name() function
* when creating your form elements. This handles the confusing stuff.
*/
function form( $instance ) {
/* Set up some default widget settings. */
$defaults = array('review' => 'http://www.example.com');
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<p>
Enter (Copy and Paste) the URLS to the pages you'd like the following menu items to link to.
</p>
<!-- Your Name: Text Input -->
<p>
<label for="<?php echo $this->get_field_id( 'review' ); ?>"><?php _e('Review:', 'example'); ?></label>
<input id="<?php echo $this->get_field_id( 'review' ); ?>" name="<?php echo $this->get_field_name( 'review' ); ?>" value="<?php echo $instance['review']; ?>" style="width:100%;" />
</p>
<?php
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment