How to Create WordPress Widget

Creating a wordpress widget can be simple or complex, it depends on what you want to achieve.

First create a widget class

{code}

class WidgetClientContact extends WP_Widget{
function WidgetClientContact(){
$widget_ops = array(‘classname’ => ‘posts-ticker’, ‘description’ => ‘Displays ticker of your posts.’);
$control_ops = array(‘id_base’ => ‘posts-ticker’, ‘width’ => 280); //default is 250 (pixel) | id_base must be the same as $this->WP_Widget first parameter
$this->WP_Widget( ‘posts-ticker’, ‘Posts Ticker’, $widget_ops, $control_ops );
}

function widget($args, $instance){
global $wpdb;
extract( $args );
$title = apply_filters(‘widget_title’, $instance[‘title’] );

echo $before_widget;
echo ‘<h3>’ . $title . ‘</h3>’; //adding <h3>The Title</title> conforms to the default wordpress widgets
echo $after_widget;
}

function update($new_instance, $old_instance){
$instance = $old_instance;
$instance[‘title’] = strip_tags( $new_instance[‘title’] );
return $instance;
}

function form($instance){
$defaults = array( ‘title’ => ‘Ads Manager’);
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<p>
<label for=”<?php echo $this->get_field_id( ‘title’ ); ?>”><?php echo LBL_PGWPAD_TITLE; ?></label>
<input id=”<?php echo $this->get_field_id( ‘title’ ); ?>” type=”text” name=”<?php echo $this->get_field_name( ‘title’ ); ?>” value=”<?php echo $instance[‘title’]; ?>”/>
</p>
<?php
}

{/code}

Then, call the class using add_action().

{code}

add_action(‘widgets_init’, ‘pgWPAdvertismentLoadWidget’);
function pgWPAdvertismentLoadWidget(){
register_widget(‘WidgetClientContact’);
}
{/code}

Where WidgetClientContact is the name of your widget class.

 

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPrint this pageEmail this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *