INSIGHTS / Article

Article / / 5 min read

Build Custom Elementor Widgets for Your Design

A step-by-step guide to building your own Elementor widgets with PHP, so editors can update content without breaking the layout.

SCND DigitalWordPress & Webflow studio
Apa itu custom widget

Elementor is a page builder plugin that gives WordPress far more layout flexibility. Many free and premium themes rely on Elementor to turn WordPress into a good-looking website.

Elementor makes it easy for users to update content. But if you know PHP, HTML, CSS, and JS, you can also build your own elements for your website. This article walks through the basic steps for creating custom elements in the Elementor plugin. You don’t need Elementor Pro to do this.

What Is a Custom Widget?

A custom widget is an Elementor widget built to the developer’s or theme author’s own specifications. With custom widgets, users can add content elements whose design and appearance have already been set by the developer.

 

What is a custom widget

What is a custom widget

When Should You Build a Custom Widget?

The main benefit of custom widgets is that the layout stays under control, with less chance of it breaking because of a mistake while editing a page. A website with a custom design is also a good reason to use custom widgets.

Make sure your design has a consistent layout, a clear structure, and sections grouped into components. With a consistent design, you can reuse the same widgets on every page of your website.

Getting Started

Create an elementor folder inside your theme, and a custom-elementor.php file inside that elementor folder. Your theme structure will look like this:

yourtheme
–elementor
–—widgets
——widget.php
——HomeHero.php
–custom-elementor.php

Add the following code to your theme’s functions.php:

require_once __DIR__ . "/elementor/custom-elementor.php";

In custom-elementor.php, use the following code:

<?php

define("CUSTOM_WIDGET_CATEGORY", "custom-widget");

/**
 * hooks for adding new category on elementor widget
 * @param ElementorElements_Manager $elements_manager
 */
function add_elementor_widget_categories($elements_manager)
{
    $elements_manager->add_category(
        'custom-widget',
        [
            'title' => esc_html__(SCND Digital Widgets', "scnd-elementor"),
            'icon' => 'eicon-kit-parts',
            'sort' => 'a-z'
        ]
    );
}
add_action('elementor/elements/categories_registered', 'add_elementor_widget_categories');

/**
 * register widgets
 * @param  ElementorWidgets_Manager $widgets_manager
 */
function register_custom_widgets($widgets_manager)
{
    require_once __DIR__ . "/widgets/widget.php";
    $widgets_manager->register(new SCNDWidgetHomeHero());
}
add_action('elementor/widgets/register', 'register_custom_widgets');

This code calls the functions that tell Elementor to register our custom widget in its editor.

Next, copy and paste the following code into elementor/widgets/widgets.php:

<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

// Include the Elementor autoloader.
$files = scandir(__DIR__);
foreach ($files as $file) {
    if ($file == "widget.php"){
        continue;
    }
    $path = __DIR__ . '/' . $file;
    if (is_file($path) && pathinfo($path, PATHINFO_EXTENSION) === 'php') {
        require_once $path;
    }
}

This code makes Elementor load the files inside the widgets folder whenever we add a line for a custom widget.

Building the Home Hero Custom Widget

HomeHeroWidget

HomeHeroWidget

As an example, we’ll build a Hero Image custom widget for the homepage. On line 29 of the custom-elementor.php code above, you’ll find this:

$widgets_manager->register(new SCNDWidgetHomeHero());

You need to create a HomeHero.php file inside the widgets folder.
Congratulations, HomeHero is your first custom widget!

Below is the HomeHero.php code for our homepage Hero widget, which has the fields Before Title, Content, Button Text, Button URL, Hero Image, and Hero Image Mobile. We’ve left out some of the fields and their HTML output to keep the code simple.

See this Elementor documentation for all the fields (Control Types) you can use in a custom widget.

The code in HomeHero.php

<?php

namespace SCNDWidget;

/**
 * HomeHero Widget
 */
class HomeHero extends ElementorWidget_Base
{

    /**
     * Summary of get_name
     * @return string
     */
    public function get_name()
    {
        return 'HomeHero';
    }

    /**
     * Summary of get_title
     * @return string
     */
    public function get_title()
    {
        return __('Home Hero', SCND_DIGITAL);
    }

    /**
     * Summary of get_icon
     * @return string
     */
    public function get_icon()
    {
        // https://elementor.github.io/elementor-icons/
        return 'eicon-device-desktop';
    }

    /**
     * Summary of get_categories
     * @return array<string>
     */
    public function get_categories()
    {
        return [CUSTOM_WIDGET_CATEGORY];
    }

    /**
     * Summary of _register_controls
     * @return void
     */
    protected function _register_controls()
    {
        $this->start_controls_section(
            'section_content',
            [
                'label' => __('Home Hero', SCND_DIGITAL),
            ]
        );

        $this->add_control(
            'BeforeTitle',
            [
                'label' => esc_html__('Before Title', SCND_DIGITAL),
                'type' => ElementorControls_Manager::TEXT,
                'default' => '',
                'label_block' => true,
            ]
        );

        $this->add_control(
            'Content',
            [
                'label' => esc_html__('Content', SCND_DIGITAL),
                'type' => ElementorControls_Manager::TEXTAREA,
                'default' => '',
                'label_block' => true,
            ]
        );

        $this->add_control(
            'HeroImage',
            [
                'label' => esc_html__('Hero Image', SCND_DIGITAL),
                'type' => ElementorControls_Manager::MEDIA,
                'default' => [
                    'url' => ElementorUtils::get_placeholder_image_src(),
                ],
            ]
        );

        $this->end_controls_section();
    }

    public function get_stack($with_common_controls = true)
    {
        return parent::get_stack(false);
    }

    /**
     * Summary of render
     * @return void
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $this->add_inline_editing_attributes("BeforeTitle", "basic");
        $this->add_inline_editing_attributes("Content", "basic");

?>
        <div class="HomeHero">
            <div <?= $this->get_render_attribute_string("BeforeTitle") ?>>
                <?= $settings['BeforeTitle'] ?>
            </div>
            <h1><?= $settings['Content'] ?></h1>

            <?php if (!empty($settings['HeroImage'])) { ?>
                <div class="HomeHeroDesktop">
                    <?php $heroImage = wp_get_attachment_image_srcset($settings['HeroImage']['id'], 'full');
                    if (!$heroImage) {
                        $image_meta = wp_get_attachment_metadata($item['HeroImage']['id']);
                        $image_srcset = wp_calculate_image_srcset(
                            array($image[1], $image[2]),
                            $image[0],
                            $image_meta
                        );
                    } ?>
                    <img src="<?php echo esc_url($image[0]); ?>" <?php if ($heroImage) : ?> srcset="<?php echo esc_attr($heroImage); ?>" <?php endif; ?> alt="<?php the_title(); ?>" />
                </div>
</div>
            <?php } ?>
    <?php
    }
}

In HomeHero, we use the Text, Content, and Image fields.

You can use many other field types in custom widgets for all kinds of purposes: text and image content, sliders, FAQ accordions, and more. To change your custom widget’s icon, use one of the icon names listed in this document.

One more tip: add the following code to your admin CSS so Elementor shows only your custom widgets:

#elementor-panel-category-pro-elements, #elementor-panel-category-basic, #elementor-panel-category-general, #elementor-panel-category-general, #elementor-panel-category-theme-elements-single, #elementor-panel-category-woocommerce-elements, #elementor-panel-category-facetwp, #elementor-panel-get-pro-elements, #elementor-panel-get-pro-elements-sticky, #elementor-panel-category-theme-elements, #elementor-panel-category-wordpress {
    display: none !important;
}

Custom widgets keep editing mistakes to a minimum, because users only get the fields and can only change the text or images in them. The layout itself is controlled by the code in our widgets.

If you have a custom design and want WordPress to make content updates easier, get in touch. We convert Figma, Adobe XD, and Sketch designs into WordPress sites. And follow us on Facebook for articles on WordPress, website design and development, case studies, effective marketing communication, and the latest digital trends.

NEED A MORE SPECIFIC ANSWER?

We’ll check your website for free.

Send us your website address. We’ll give you a picture of its condition and recommendations you can act on right away.

Check my website