WordPress / WordPress Widgets and Menus
Custom Widgets
In this tutorial, you will learn how to create your own custom widgets in WordPress. We'll start by discussing what custom widgets are, why they're useful, and then guide you thro…
Section overview
4 resourcesCovers the use of widgets and menus to enhance site functionality and navigation.
1. Introduction
In this tutorial, our goal is to learn how to create custom widgets in WordPress. WordPress widgets are small blocks that perform specific functions. They can be added to widget-ready areas of your WordPress site like the sidebar, footer, and other locations. Custom widgets allow you to add more specific functionality to your site that may not be available with default widgets.
By the end of this tutorial, you will be able to:
- Understand what custom widgets are and why they're useful
- Create your own custom widgets in WordPress
Prerequisites
Before we proceed, you should have a basic understanding of:
- WordPress (how to install and use it)
- PHP (the programming language used to create WordPress themes and plugins)
- HTML/CSS (to design and style your custom widget)
2. Step-by-Step Guide
To create a custom widget in WordPress, you have to create a child theme or a plugin where you'll place your custom code. For simplicity, we'll create a child theme.
Create a Child Theme
- Step 1: Create a new directory in your themes directory
- Step 2: Create a
style.cssfile in the new directory - Step 3: Add a Theme Header in the
style.cssfile - Step 4: Enqueue Parent and Child theme stylesheets
Create a Custom Widget
- Step 1: Create a PHP file in your child theme directory and name it
custom_widget.php - Step 2: In this file, define a class that extends the
WP_Widgetclass - Step 3: Define four methods within this class:
__construct(),widget(),form(), andupdate() - Step 4: Register your custom widget
3. Code Examples
Below are the code examples for the aforementioned steps:
- Creating a Child Theme
/* Step 1: Create a new directory in your themes directory. Let's call it 'mytheme-child' */
/* Step 2: Create a style.css file in the new directory and add the following: */
/*
Theme Name: My Child Theme
Template: twentynineteen
Version: 1.0.0
*/
/* Step 3: Enqueue Parent and Child theme stylesheets. Add the following code in your functions.php file */
function my_theme_enqueue_styles() {
$parent_style = 'parent-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
- Creating a Custom Widget
/* Step 1: Create a PHP file in your child theme directory and name it 'custom_widget.php'
/* Step 2: In this file, define a class that extends the WP_Widget class. */
class My_Custom_Widget extends WP_Widget {
/* Step 3: Define the four methods */
// The construct function
function __construct() {
parent::__construct(
// Base ID of your widget
'my_custom_widget',
// Widget name will appear in UI
__('My Custom Widget', 'my_custom_widget_domain'),
// Widget description
array( 'description' => __( 'A Custom Widget', 'my_custom_widget_domain' ), )
);
}
// Creating widget front-end
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
// Before and after widget arguments are defined by themes
echo $args['before_widget'];
if ( ! empty( $title ) )
echo $args['before_title'] . $title . $args['after_title'];
// This is where you run the code and display the output
echo __( 'Hello, World!', 'my_custom_widget_domain' );
echo $args['after_widget'];
}
// Widget Backend
public function form( $instance ) {
if ( isset( $instance[ 'title' ] ) ) {
$title = $instance[ 'title' ];
}
else {
$title = __( 'New title', 'my_custom_widget_domain' );
}
// Widget admin form
?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
</p>
<?php
}
// Updating widget replacing old instances with new
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
return $instance;
}
} // Class my_custom_widget ends here
/* Step 4: Register your custom widget */
// Register and load the widget
function my_load_widget() {
register_widget( 'my_custom_widget' );
}
add_action( 'widgets_init', 'my_load_widget' );
4. Summary
In this tutorial, we learned about custom widgets in WordPress and how to create them. We discussed the importance of custom widgets and walked through the process of creating a child theme, defining a custom widget class, and registering the widget.
Next, you can explore more about widget customization, learn about widget styling, and experiment with adding more complex functionalities to your custom widgets.
WordPress Codex and Developer Resources are great places to learn more about WordPress development.
5. Practice Exercises
-
Create a custom widget that displays a personalized greeting message. The message should change based on the time of day (Morning, Afternoon, Evening).
-
Create a custom widget that displays the latest 5 posts from your WordPress site.
-
Create a custom widget that allows users to subscribe to your newsletter. It should include a form for users to enter their email addresses.
Solutions for these exercises are not provided as they are meant to be a practice for learners. However, all the knowledge required to solve these exercises has been provided in the tutorial. For further practice and learning, you can try modifying the existing widgets and observe the changes.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article