WordPress Widget

Introduction

WordPress widget is created by instantiating a class that has a rather large code, so when creating a new widget, a prepared template is used that can be easily adapted to needs. The Custom class inherits WordPress’s widget class WP_Widget(). You can see more about the WP_Widget() class on the official page https://developer.wordpress.org/reference/classes/wp_widget/.

The basic skeleton of the widget class

The skeleton of the new class consists of four functions and looks like this:

Hanging a widget on a hook:

or another way but with the same result:

Clarification of functions within the class

image

image ×

Function “__construct”

The “__construct()” function is responsible for the appearance of our widget in the “Available Widgets” section, along with other standard widgets. In addition to activating the function, it specifies a name, a short description and an identification string. Hooks for other functions can also be registered and activated within this function. The __construct() function extends the constructor inside the WP_Widget superclass.

The parameters of the constructor function within the WP-Widget class are:

We define these parameters from our custom widget class via parent::__construct():

Example

For greater template automation, we can define the values of the $widget_slug variable and provide easy calling of the variable within our class using the get_widget_slug() function.

Function “form”

This function is responsible for printing the content of the widget form on the admin page (when it is dragged to the widget area). Properties of the instantiated widget are stored in the $instance array. We can add default values ​​to this string, while all other values ​​are obtained through form field input. In order for the variable $instance to be an array, we use the expression “(array) $instance” so called. casting (eng.casting).

Form field values are members of the $instance array and can be accessed using the key array e.g. $instance[‘title’]

  • Default values in the form of a string $defaults

    Default values are defined in the form of a key/value string (e.g. $defaults):

  • Joining two strings

    After that, let’s concatenate the two strings using the wordpress function “wp_parse_args($instance, $defaults)”. This function will concatenate the arrays ($instance and $defaults) so that the values ​​of the array $defaults are overwritten if they exist in the array $args.

  • Widget form

    image

    image ×
    • Dynamic form elements

      Within the form, it is necessary that some parameter (eg field ID) has dynamic values that will be different for each new instance of the widget. This is achieved with a methodand the WP_Widget class:

      • get_field_id().
      • get_field_name()
    • Radio button and Check box

      If a check box or radio button is used in the form, then the command checked($checked, $current) is used, which compares two values: the last saved value and the current value of the field. If both are checked, the checked-“checked” attribute is added. See more about this function at codex.wordpress.org/Function_Reference/checked

    • Dropdown menu

      When using the dropdown menu, selected( $selected, $current) is used, which compares two values: the last saved value and the current value of the field. If both are checked, the selected=”selected” attribute is added. More about this function at codex.wordpress.org/Function_Reference/selected

    • Preventing XSS attacks (eng.escaping)

      When writing the code of the form, pay attention to escaping entries

Example

Function “update”

This function is activated every time we press save. It saves some data in the field if it is entered and prints it in the form. Two parameters of the parent class WP_Widget():

are used

  • string $new_instance – New settings for this instance as input by the user via WP_Widget::form()
  • string $old_instance – Old settings for this instance

Within this function, in addition to saving the entered data, validation (eng.validation) and cleaning (eng.sanitize) of the entries from the form are done in parallel.

Example

Function “widget”

This function is responsible for printing widgets on the user’s public page. Within the WP_Widget superclass, the $args parameter is an array (key/value) whose members are:

  • ‘before_title’=> ‘ ‘
  • ‘after_title’=> ‘ ‘
  • ‘before_widget’=> ‘ ‘
  • ‘after_widget’=> ‘ ‘

The members of this array are transferred to variables with the function extract():

After which we can use variables:

  • $before_title
  • $after_title
  • $before_widget
  • $after_widget

Everything that needs to be printed is stored in the variable $widget_string”. We can use the functions “ob_start() and ob_get-clean()” or simple string concatenation.

Template class for creating widgets

This custom widget class template was created by modifying the code of the original template “Widget Boilerplate” by Tom McFariln. The entire code of the template can be copied into functions.php, but a better solution is to separate it into a separate file and call it in functions.php with the command:

After copying the template code, we should adapt the code to our needs, change the names in the places where the word “prosystem” appears, and add part of the code in the places “add_code”.

Widget inside the plugin

Plugin structure

If we make a widget as part of a plugin, the template is supplemented with additional elements related to the plugin. So the plugin folder structure looks like this:

  • css
    • admin.css
    • widget.css
    • sass
      • admin.scss
      • widget.scss
  • js
    • admin.js
    • widget.js
  • lang
    • plugin.po
  • views
    • admin.php
    • widget.php
  • Prosistem-Widget-Boilerplate.php

Css files style the appearance of the plugin, on the admin page admin.css while widget.php styles the final appearance of the widget on the public page of the site. Similarly for javascript files, admin.js contains scripts used for display on the admin page while widget.js contains scripts for display on the public user page of the site. The folder “lang” stores files related to plugin translation.

The folder “view” contains files containing selected parts of the php code. In the file admin.php there is a separate part from the function “form” which is responsible for printing the content inside the widget form when it is dragged to the widget area within the admin page. While in the widget.php file, the part from the “widget” function is separated.

Widget class template for plugin

This template contains all the code previously explained, but has an additional part that will register and load scripts, css files and files related to plugin translation.

You can view the original code by Tom McFarlin on his github account github.com/tommcfarlin/WordPress-Widget-Boilerplate/tree/master/widget-boilerplate