By Writing Code in the Theme’s functions.php File
For more control, you can create custom widgets by adding code to your theme’s functions.php file. This approach requires basic PHP and WordPress coding knowledge.
Step 1: Open functions.php:
- Navigate to your theme’s directory.
- Open functions.php in a code editor.
Step 2: Add Widget Code:
- Define a new widget class that extends WP_Widget.
- Register the widget using widgets_init action hook.
Example: Add to functions.php. Save the functions.php File and go to “Appearance” > “Widgets” in your WordPress dashboard. You should see “My Custom Widget” available to add to your sidebar.
// Define the widget class
class My_Custom_Widget extends WP_Widget {
// Widget settings and initialization
function __construct() {
parent::__construct(
'my_custom_widget',
esc_html__('My Custom Widget', 'text_domain'),
array('description' => esc_html__('A Custom Widget',
'text_domain'), )
);
}
// Front-end display of widget
public function widget($args, $instance) {
echo $args['before_widget'];
if (!empty($instance['title'])) {
echo $args['before_title'] . apply_filters('widget_title',
$instance['title']) . $args['after_title'];
}
echo esc_html__('Hello, World!', 'text_domain');
echo $args['after_widget'];
}
// Back-end widget form
public function form($instance) {
$title = !empty($instance['title']) ? $instance['title'] :
esc_html__('New title', 'text_domain');
?>
<p>
<label for="<?php echo esc_attr($this->get_field_id('title')); ?>">
<?php esc_attr_e('Title:', 'text_domain'); ?></label>
<input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>"
name="<?php echo esc_attr($this->get_field_name('title')); ?>"
type="text" value="<?php echo esc_attr($title); ?>">
</p>
<?php
}
// Save widget form values
public function update($new_instance, $old_instance) {
$instance = array();
$instance['title'] = (!empty($new_instance['title'])) ?
strip_tags($new_instance['title']) : '';
return $instance;
}
}
// Register the widget
function register_my_custom_widget() {
register_widget('My_Custom_Widget');
}
add_action('widgets_init', 'register_my_custom_widget');
Output: After adding the code to functions.php, the widget will be available in the “Widgets” section of the WordPress admin, ready to be dragged into any widget area.
How to Create WordPress Custom Widgets?
Creating custom widgets in WordPress can significantly enhance your website’s functionality by allowing you to add specific features and content to your sidebar or other widgetized areas. This article will guide you through the process of creating custom widgets, explaining different approaches and providing clear examples for each method.
There are three primary approaches to creating custom widgets in WordPress:
Table of Content
- By using a plugin
- By Writing Code in the Theme’s functions.php File
- By using a Custom Plugin
Contact Us