how to add custom widget in wordpress theme

how to add custom widget in wordpress theme

wordpress widget and sidebar is different things. Here in this article we will show you how to add custom widget in wordpress theme using your theme code.

Some years ago I searched for creating the widget in wordpress theme But I did not get the perfect answer. Every time I got code snippet of sidebar. Many WP developers are assuming widget means sidebar. wordpress widget and sidebar is totally different things. Here in this article I will show you how to create the wordpress widget using your theme code.

how to add custom widget in wordpress theme

You can put following code into functions.php file or you can create sperate file and just include that into functions.php file.

class RecentPostWidget extends WP_Widget
{
function RecentPostWidget()
{
$widget_ops = array('classname' => 'RecentPostWidget', 'description' => 'Displays a Recent post with thumbnail' );
$this->WP_Widget('RecentPostWidget', 'Recent Post and Thumbnail', $widget_ops);
}

function form($instance)
{
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
$title = $instance['title'];
?>
<?php echo $this->get_field_id('title'); ?>">Title: <input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" />

<?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;;

// WIDGET CODE GOES HERE
echo "<h1>This is my new widget!</h1>";

echo $after_widget;
}

}
add_action( 'widgets_init', create_function('', 'return register_widget("RecentPostWidget");') ); ?>

Following is screen-shot of sample widget code which I used in functions.php file.

Add widget in wordpress theme
Add widget in wordpress theme

If you are looking for sidebar through theme then check following articles:
https://purabtech.in/create-multiple-widgets-wordpress-theme/
https://purabtech.in/add-sidebar-twenty-thirteen-wordpress-theme/

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.