Here I am sharing a best and easiest way to create your own custom widgets with your own custom code in WordPress. In one of my old post I have already shared the way to Create custom widget area, so if you like you can also go through it.
Before moving to the core code I would like to share that basically Widgets are the small application that can be installed/coded and executed within a web page, they are derived from the idea to re use the code and allow users to turn personal content into dynamic web applications.
Here in my example I am sharing the base to create custom widget in WordPress. But you can place your own code as per your requirement just by replacing “// CUSTOM WIDGET CODE GOES HERE” in the below code. So might be you can prepare a widget to display latest 5 blog posts, random posts or else.
So what you simply have to do is – Place the bellow code in function.php of you activated theme folder
<?php
class mycustomwidget extends WP_Widget
{
function mycustomwidget()
{
$widget_ops = array('classname' => 'mycustomwidget', 'description' => 'This is my own customized widget' );
$this->WP_Widget('mycustomwidget', 'My Custom Widget', $widget_ops);
}
function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = $instance['title'];
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
}
function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
return $instance;
}
function widget($args, $instance)
{
extract($args, EXTR_SKIP);
echo $before_widget;
$title = empty($instance['title']) ? ' ' : apply_filters('widget_title', $instance['title']);
if (!empty($title))
echo $before_title . $title . $after_title;;
// CUSTOM WIDGET CODE GOES HERE
echo "<h1>This is my new widget!</h1>";
echo $after_widget;
}
}
add_action( 'widgets_init', create_function('', 'return register_widget("mycustomwidget");') );?>
Just don’t forget to add your own code in place of // CUSTOM WIDGET CODE GOES HERE and if you like you can also change the class name from “mycustomwidget” to what you like.
Enjoy you wordpress custom widget.