This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Cloudways Copilot is here. Get Access to your Intelligent Hosting Assistant Today! Learn More

How to Create Custom Widgets on WordPress in 2024 [Easy Guide]

Updated on December 6, 2024

9 Min Read

WordPress widgets let you add features like text, pages, social buttons, and elements to designated areas (sidebars) of your website. For example, a newsletter sign-up form in the sidebar.

These elements help you enhance your site without changing the main content, giving you the flexibility to add things like banners, ads, or navigation tools.

Some of the default widgets included with the WordPress installation are archives, calendars, categories, tag clouds, pages, meta, and more. You can also customize widgets for a personal touch, such as embedding social media feeds, recent posts, or HTML tags.

In this post, I’ll show you how to create a WordPress custom widget in three different ways and how to add or remove widgets from specific posts or pages.

Let’s get started…

What Is a WordPress Widget?

WordPress widgets are small blocks of content that can be added to specific areas of your website, like sidebars or footers. Each widget is essentially a PHP object that outputs HTML, allowing for a range of functionalities, such as displaying recent posts, embedding social media feeds, showcasing categories, or adding custom menus.

Widgets can be reused multiple times within the same widget area, allowing for flexibility in design. Depending on the theme, there may be multiple widget areas.

WordPress widgets can also save configuration settings in the database, making it easy to manage their behavior and appearance.

What Can You Use WordPress Widgets For, and Where Can You Add Them?

Widgets can enhance your site’s functionality in various ways. For instance, you can add a search box for easy content discovery or an email subscription form to gather sign-ups.

You can showcase your latest posts or highlight your most popular content to keep visitors interested.

You can also include social media follow buttons or a live feed of your recent posts.

Additionally, you can display an author bio to connect with readers, and listing your categories can simplify navigation. If you host events, you can use a calendar widget to show upcoming dates, and for eCommerce sites, widgets can help implement product filters.

As for where to add widgets, they can be placed in any “widget area” on your site. Most themes have common areas like the sidebar and footer, but some may offer additional spaces. These options are accessible in the WordPress widget interface, allowing for straightforward customization of your site’s layout.

Why Include a Widget on a WordPress Page or Post?

Adding a widget to a WordPress page or post helps you enhance your site with relevant content. You can promote offers, grow your email list, or make navigation easier with additional menus or search boxes. Widgets are also useful for adding ads or highlighting new content without being distracting.

How Do Custom Widgets Function in WordPress?

Custom widgets in WordPress function by using the WP Widget class, allowing developers to display dynamic content on their sites. Each widget operates by defining its output and settings through specific functions.

To create a functional widget, four key functions are typically required:

  • The __construct() function initializes the widget and defines its parameters.
  • The widget() function determines the content displayed to users.
  • The form() function creates an interface in the WordPress dashboard for setting up the widget’s options.
  • Lastly, the update() function saves any changes to those settings, ensuring your widget shows the latest information.

 

There are about 20 functions available in the WP Widget class, but focusing on these four core functions is enough to create a functional custom widget. For advanced options, you can check out WordPress developer documentation for more features.

How to Create a WordPress Custom Widget?

Since we don’t have the option to add widgets default to our theme, we can add the option manually with our custom code. You can achieve this via SSH or SFTP. Either way is fine. Here’s a screenshot of the default WordPress theme missing the widgets option:

  • To make the widgets option appear in our theme, we will need to access our application file via an SFTP client such as FileZilla. For this tutorial, I’ll be using Filezilla. If you are a Cloudways user, you can access web files more easily using the built-in SSH terminal on the Cloudways platform.
  • Once you access the application, you must go to the wp-content folder to access your theme’s folder. To check your active theme, you can visit your wp-admin to confirm the theme under the appearance tab before making any changes. In my case, I’m using the twentytwentyfour theme.
  • You will need to modify the functions.php file. You can either download it to have a copy of the original file or modify it by editing it directly. It’s good to keep a copy of the file.

Step 1: Register a Custom Sidebar in Your Theme

To start, we’ll add a new sidebar area that you can use to display custom widgets. Follow these steps to register the sidebar:

Add the following code to the bottom of the functions.php file in your theme:

function my_custom_sidebar() {
    register_sidebar(array(
        'name'          => __('Custom Sidebar', 'text_domain'),
        'id'            => 'custom-sidebar',
        'description'   => __('Widgets in this area will be shown on the homepage.', 'text_domain'),
        'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widget-title">',
        'after_title'   => '</h2>',
    ));
}
add_action('widgets_init', 'my_custom_sidebar');

Explanation: This code registers a sidebar named “Custom Sidebar” which will appear in the WordPress admin under Appearance > Widgets. It defines the HTML structure for each widget in the sidebar.

Step 2: Create a Custom Widget

Next, let’s create a custom widget that can be displayed in the new sidebar. Add the following code to your functions.php file after the sidebar registration code.

class My_Custom_Widget extends WP_Widget {
    function __construct() {
        parent::__construct(
            'my_custom_widget', // Base ID
            __('My Custom Widget', 'text_domain'), // Name
            array('description' => __('A Custom Widget for Homepage', 'text_domain')) // Args
        );
    }

    public function widget($args, $instance) {
        echo $args['before_widget'];
        $title = apply_filters('widget_title', $instance['title']);
        if (!empty($title)) {
            echo $args['before_title'] . $title . $args['after_title'];
        }
        echo '<p>Hello, this is my custom widget!</p>'; // Customize this content
        echo $args['after_widget'];
    }

    public function form($instance) {
        $title = !empty($instance['title']) ? $instance['title'] : __('New title', 'text_domain');
        ?>
        <p>
            <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Title:'); ?></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
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : '';
        return $instance;
    }
}

function register_my_custom_widget() {
    register_widget('My_Custom_Widget');
}
add_action('widgets_init', 'register_my_custom_widget');

Explanation: This code defines a new widget class, My_Custom_Widget, which includes:

  • widget(): The content that will be displayed in the sidebar. Customize this section to show any content you’d like.
  • form(): A form that lets users set a title for the widget.
  • update(): Saves the form data when updated.

The function register_my_custom_widget() registers this widget, making it available in Appearance > Widgets.

Step 3: Add the Sidebar to Your Theme’s Template

Now, we need to modify your template file (e.g., index.html or home.html) to display the new sidebar. You’ll usually find these files in the theme’s main folder.

  1. Open index.html or home.html in the theme’s folder.
  2. Replace the content in the file with the following code, making sure to add the dynamic sidebar placeholder where you want it displayed:
<!-- wp:template-part {"slug":"header","area":"header","tagName":"header"} /-->

<!-- wp:group {"tagName":"main","align":"full","layout":{"type":"constrained"}} -->
<main class="wp-block-group alignfull">
    <!-- wp:heading {"level":1,"align":"wide","style":{"spacing":{"padding":{"top":"var:preset|spacing|50"}}}} -->
    <h1 class="wp-block-heading alignwide" style="padding-top:var(--wp--preset--spacing--50)">Posts</h1>
    <!-- /wp:heading -->
    
    <!-- wp:pattern {"slug":"twentytwentyfour/posts-3-col"} /-->

    <!-- Dynamic Sidebar -->
    <!-- wp:dynamic-sidebar {"id":"custom-sidebar"} /-->
</main>
<!-- /wp:group -->

<!-- wp:template-part {"slug":"footer","area":"footer","tagName":"footer"} /-->

Explanation: This code adds the header, main content area, and footer. The key addition here is the dynamic sidebar (<!– wp:dynamic-sidebar {“id”:”custom-sidebar”} /–>), which displays the registered sidebar and your custom widget.

Step 4: Verify the Changes in wp-admin

After completing the above steps:

1. Go to Appearance > Widgets in the WordPress admin area.

2. You should see the Custom Sidebar with the My Custom Widget option available.

3. Add the widget to your Custom Sidebar, customize the title, and save the widget.

Once saved, visit the front end of your site to verify that the widget displays as expected.

How to Insert a Widget in WordPress?

To add a widget in WordPress, follow these simple steps:

1. Go to the Widgets Interface
From your WordPress dashboard, navigate to Appearance → Widgets. This will open the widget management screen.

2. Select a Widget Location
Once you’re in the widget interface, you’ll see different areas where you can add widgets. These areas depend on your WordPress theme. Click the arrow next to the area you want to edit to expand it.

3. Add Content Using Blocks
After selecting the widget area, you can add content using the familiar block editor. Just click the plus icon to insert a block, choosing from built-in WordPress blocks or any custom blocks from your plugins. Once added, you can adjust the block’s settings, such as the number of posts to display or featured image options.

4. Save Your Changes
Once you’re satisfied with how everything looks, click the Update button to save your changes. Your widgets will be live on your website immediately.

If you don’t see the Widgets menu, you might be using a WordPress block theme, which handles design through the Site Editor instead. We have a blog on WordPress full site editing that you should definitely check out.

How to Delete a Widget in WordPress?

For this example, we can delete the widget we added earlier. To do this, select the block widget, click the three-dot menu in the toolbar, and choose “Delete.”

How to Use the WordPress Customizer to Manage Widgets?

You can also manage widgets through the WordPress Customizer, which allows you to see a real-time preview of your changes on your website. Here’s how to do it:

  • Navigate to AppearanceCustomize in your WordPress dashboard.

  • In the Customizer sidebar, select Widgets.

  • Choose the widget location from the list of available options (you’ll only see locations visible on the current page you’re previewing).

  • Add or edit widgets using the interface provided.

  • Additionally, you can click the pencil icon on the live preview to customize a specific widget directly.

How to Show a WordPress Widget on a Specific Post or Page?

By default, any widgets you add to your site will be displayed throughout all areas where that widget space is available. For instance, if you place a widget in your main sidebar, it will show up on every page that features a sidebar.

However, there may be times when you only want to display widgets on specific content, like a particular post, page, or even a category or tag.

If you’re using block widgets, you can easily control where they appear by using a plugin that adds visibility conditions, such as Block Visibility.

  • After installing and activating the plugin, navigate to the widget interface and locate the widget you want to customize.

  • When you edit this widget, a new Visibility section will appear in the sidebar settings.

  • In this area, you can set rules for when to show or hide the widget, such as displaying it only on a specific post.

Conclusion

Creating custom WordPress widgets lets you add specific features to your site, like personalized content displays, improved navigation, or custom tools like social media feeds or search bars.

I hope that by following the steps in this guide, you can build widgets that meet your unique needs and enhance your website’s user experience. If you have any questions about WordPress development, please comment below and I’d be happy to help.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Sarim Javaid

Sarim Javaid is a Sr. Content Marketing Manager at Cloudways, where his role involves shaping compelling narratives and strategic content. Skilled at crafting cohesive stories from a flurry of ideas, Sarim's writing is driven by curiosity and a deep fascination with Google's evolving algorithms. Beyond the professional sphere, he's a music and art admirer and an overly-excited person.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour