Create widgets. How to Create Widgets for WordPress

In the last lesson you learned how to create your own own sidebar, and in this lesson you will learn how to create your own widget on WordPress. A widget is a module that is designed specifically for placement on a sidebar.

Why do we need widgets at all? They are needed for the orderly placement of auxiliary content on the site, as well as its further editing. For example, very often widgets contain links, advertising blocks, subscription forms and other important information.

On WordPress There are already standard widgets that can be seen on the left side of the admin console. On the tab - Appearance/ Widgets, the right side is occupied by sidebars, where you can drag and drop all available widgets with the mouse.

How to create your own widget on WordPress

Let's open WordPress code and let's see what the documentation has about creating your own widget. WordPress proposes to extend the standard class WP_Widget and its functions and demonstrates an example of finished code with a single text field. New_Widget extends built-in WordPress widget WP_Widget.

Class New_Widget extends WP_Widget (

Code for creating a new widget with default name Foo_Widget, you need to replace this name everywhere with yours - New_Widget.

We need to add a new class New_Widget, copy the code from Example in the code and paste it into the file function.php. You also need to register a new widget, this is done using a hook widgets_init, the hook hooks the added widget to the core WordPress. Below is an example of widget registration New_Widget, add this code to the file function.php, right after the code with the class.

Function register_new_widget() (
register_widget("New_Widget");
}
add_action("widgets_init", "register_new_widget");

Now our widget has appeared in the area of ​​available widgets, which can be added to the desired place in the sidebar.

We can see the widget we created on the website. The new widget is absolutely useless, since it only displays the title, but it was important for me to show the principle of creation itself.

The function.php file is not rubbery

If you have too much custom code, then I recommend putting the code for each new widget class into a separate one PHP file, which should be placed in its own separate folder with widgets. In addition, for the registration code for all custom widgets, you need to create another file. Now we need to connect these files to function.php via function require.

Require get_template_directory() . "/widgets/custom-widget-1.php";
require get_template_directory() . "/widgets/custom-widget-2.php";

How to disable widgets

If you are not going to use any standard or custom widgets, you can disable them. For this purpose WordPress function is provided - unregister_widget(), it does not remove widgets from WordPress forever, and they are simply removed by their admin console. Paste to file function.php names of widgets that you need to disable.

Function remove_calendar_widget() (
unregister_widget("WP_Widget_Calendar");
}

And also don’t forget to remove the hook that connects to the kernel WordPress.

Add_action("widgets_init", "remove_calendar_widget");

If you are a beginner web developer, of course you can use ready-made plugins with widgets. From my own experience, I know which widgets are most in demand on websites now.

Contact Form 7 - feedback form plugin

This plugin is the most popular, although it does not create its own widget, but all the forms you create have their own shortcode. You copy the shortcode of the desired form and paste it into the text widget in the mode "Text" this shortcode.

A widget with a ready-made feedback form will appear on the site in the sidebar.

Widgets in WordPress make it easier for users to place elements on their site. There are many different WordPress themes and plugins that use widgets to allow users to create their own layouts. There are various plugins to improve widget management. In this article, we will show you how to create a custom widget for your WordPress site.

What is a WordPress widget?

Widgets were created to provide simple way managing the design and structure of materials in a WP theme. The good thing about widgets is that you can drag and drop them into your sidebar or any widget-ready areas of your site. They provide great flexibility to plugins, which is why theme developers use them so often. allow developers to add functionality to their products, allowing users to access it without having to write any code.

Of course, as a user, you can always create your own, which you can later use in any theme.

Creating a Widget in WordPress

The widget code can be styled in two ways: either add it to your theme's functions.php file, or create a separate functionality plugin.

In this tutorial, we'll create a simple widget that simply welcomes visitors. Copy the following code and place it in your theme's plugin or functions.php.

// Creating the widget class wpb_widget extends WP_Widget ( function __construct() ( parent::__construct(// Base ID of your widget "wpb_widget", // Widget name will appear in UI __("WPBeginner Widget", "wpb_widget_domain") , // Widget description array("description" => __("Sample widget based on WPBeginner Tutorial", "wpb_widget_domain"),)); ) // Creating widget front-end // This is where the action happens 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!", "wpb_widget_domain "); echo $args["after_widget"]; ) // Widget Backend public function form($instance) ( if (isset($instance[ "title" ])) ( $title = $instance[ "title" ]; ) else ( $title = __("New title", "wpb_widget_domain"); ) // Widget admin form ?>

" name="get_field_name("title"); ?>" type="text" value="!}" />

Now go to Appearance - Widgets and drag the WPBeginner Widget into your sidebar to see it in action.

Pretty simple, isn't it? First we create a custom widget. We then define what exactly the widget does and how it is displayed in the backend. We then determine how changes made by the widget should be handled. Finally, we register and load the widget.

There are some things in this code that may make you question. Let's say, for example, what wpb_text_domain does. WordPress uses gettext to handle translation and localization. So: wpb_text_domain and __e indicate to gettext that these strings are available for translation. , see our guide.

We all use widgets in one way or another, because they are the domain of the Android system, even iPhone owners secretly glance at them. What widgets do you use? The clock, the weather – it’s all “business”, right? You probably have Beautiful Widgets, Premium Widgets or similar applications installed. These programs are of course good, but they don’t allow your creative abilities to run wild. Would you like to create a widget for your smartphone yourself? Then let's see how this can be done using the Editor widgets application.

We take a beautiful background, a large watch dial, the day of the week, but what about without the weather? And we’ll add it to our ideal widget, and for 3 days at once. So, all this and much more can be done using the Editor widgets android app. Let's start creating.

[

By default, we have eight widget layouts, choose one and start creating. Here no one limits us in our possibilities. Choose a background. This can be either a picture or a color fill; you can adjust the transparency of the layer. Choosing a frame. There are quite a lot of them and they are all very beautiful, of course in taste and color... Then we move on to filling our widget. To do this, we have access to various elements: clock, day of the week, date, battery charge in several projections, notifications of missed calls and messages, weather elements. As you understand, the choice is very wide. We take what we need and arrange it the way we need it. We can also change the color of an object and the font style. In general, we create complete beauty, and everyone has their own beauty - after all, we are all unique!

The Editor widgets application creates ideal conditions. Therefore, the result of the work depends only on the flight of our imagination.

Widgets can have different sizes and are scalable.

By the way, in the settings we can select the time and date format. And also set some “action” when you click on the widget. This could include additional information about the state of the phone, or the launch of a pre-selected application, for example, a voice recorder. Or dial a telephone number, which is even more unusual, but perhaps useful to someone.

In general, if you want to create a widget for your Android device, then Editor widgets will be your faithful assistant.

AppWidget, or simply “widget,” is one of the most impressive and convenient user interface elements in the Android operating system, which can be added to the desktop for quick access to certain functions of the corresponding application. In this article we will figure out how to create your own widget.

What is a widget structurally? A widget is needed to display certain information related to the application to which it belongs, or to quickly interact with this application directly through the desktop. The simplest example is a clock on a desktop. Naturally, widgets can be easily added or removed from desktops.

High-quality widgets significantly optimize interaction with the device. Moreover, very often the most convenient widgets take up the least space on the desktop, and at the same time are the most informative. Almost any user will try to place the maximum amount of information on the desktop of their Android gadget, and the important point is that space is limited.

Let's start creating the widget with the design. Fortunately, Google has provided very useful UI Guidelines for software developers, which describe in detail the design creation process and the basic principles of ergonomics. There is also a separate official instruction for creating widgets, which can be found at the link: //developer.android.com/guide/practices/ui_guidelines/widget_design.html.

A widget that occupies one “cell” on the desktop has a resolution of 80x100 pixels, respectively, to create an oblong widget 4 cells long and one cell high, you need, respectively, 320x100 pixels. We will take this size as the basis for the widget we create.

Now the widget needs to be drawn. In principle, a widget may well not have any graphic part, and display only text or controls, without a background or frame, but, naturally, a beautiful and pleasing to the eye widget simply must have a high-quality design. So let's draw the background. Let's take the background from the above-mentioned UI Guideline as a basis. We open the template available to us in Photoshop or another graphics editor and do whatever we want, after which we save the resulting image in .png format. The format we need is PNG-24, with 8-bit color and a transparent background. So the basis for our widget is ready.

Now let's move on to creating the software part. The widget may not have a software part. Simply put, it will be in the add widgets menu, but not in the main application menu. We will create exactly this type of widget. We create a new project, and for convenience we name it so that the main class is named widget.java.

Editing AndroidManifest. xml. We declare our widget:

package="com.example.widget"

android:versionCode=”1″

android:versionName=”1.0″>

android:resource=”@xml/widget_info” />

Now let's edit widget.java. Here it is necessary to describe how the widget will react to various conditions. The AppWidgetProvider class has the following methods:

onUpdate – the method is called when the widget is created, as well as after a specified time. The time is set in the configuration file of this widget. Note that it is used most often.

onDeleted – the method is executed when a widget is deleted from the desktop.

onEnabled – the method is called when the widget is activated for the first time. But if another exactly the same widget is added, this method is no longer executed.

onDisabled – the method is executed when the last copy of the widget is deleted from the desktop. Accordingly, this method is the reverse of onEnabled.

onReceive – the method is called simultaneously with all others. Often not used at all.

We will not delve too deeply into the software part of the widget, and therefore we will not overfill our example with any handlers, but will simply implement all the functionality using Layouts. You must declare the AppWidgetProvider class as follows:

package com.example.widget;

import android.appwidget.AppWidgetProvider;

public class widget extends AppWidgetProvider(

}

Next, we describe our widget - this is necessary so that the mobile device understands what it is dealing with. To do this you need to create a folder xml in folder res. In it we create a file with the name widget_ info. xml. Open the created file and write the following code into it:

android:minWidth=”294dp”

android:minHeight=”72dp”

android:updatePeriodMillis=”0″

android:initialLayout="@layout/widget">

Here is a brief description of the specified parameters:

minWidth – the minimum width required for the widget to work.

minHeight – the minimum height required for the widget to work.

updatePeriodMillis – the period during which the widget is updated, specified in milliseconds. The parameter is very useful, since after the specified time period has passed, the onUpdate method of the AppWidgetProvider object is triggered.

initialLayout – the parameter points to a resource describing the interface of our widget.

The formula for calculating the size of a widget is as follows: (number of cells * 74) - 2.

Let's start describing the interface of the widget we are creating. This is where the previously created background comes in handy. Import the background image into the folder dwawable(or in all three folders drawable for different screen resolutions). In folder layout create a file named widget. xml. The interface is described as for regular Activity, but there are some limitations. The following elements are allowed for use:

Let's create a LinearLayout, to which we will apply the created background image and add AnalogClock for example. The watch itself will not fit into the frame, but it will do just fine as a visual example. So:

android:id=”@+id/Widget”

android:layout_height="fill_parent"

android:orientation=”horizontal”

android:gravity=”center_vertical”

android:background=”@drawable/frame”>

android:layout_width="fill_parent"

android:layout_height="wrap_content"/>

May 21 , 2016

Every time I connect a ready-made solution from services like disqus or Google analytics to my websites, I am amazed at the ease of integration of quite complex functionality. I put 3 lines of javascript code into the code - and you already have a block with comments. 2 more lines - and analytics from Google or Yandex are available. Of course, no magic happens; those same 3 lines of code pull all the necessary code from the remote server, and essentially deploy a small web application on the pages of your site. But how does it work inside and how can you do it yourself? It was quite interesting to figure this out, and in the end I got a small widget that works exactly according to this simple embedding scheme and at the same time does some useful things. Further details.

Why do we need widgets?

Iframes are well suited for this purpose. These are actually separate html pages that are embedded into other pages without having access to their “parent”. That is, we can embed our web application into an iframe, which will quietly do its job without interfering with the main site. And what exactly your widget will do, build a comment system on the page, show a cool toy or draw an interactive advertising banner - is entirely a matter of your taste and imagination.

In this article, we won’t focus on the toy, but will look at how to create an embedded widget for determining the weather. Of course, there are many different weather services for this, but we are not interested in using a ready-made solution. I would like to create a simple widget with my own hands in order to understand how it generally works and in the future apply the knowledge for some useful things. At the same time, we’ll refresh our knowledge of native javascript and php along the way.

What do we do?

We will create a widget that draws a shape with the weather forecast for tomorrow. Let's take only the temperature as an example, but as you will see further, it will be easy to add other data. The widget will contain information about the temperature for tomorrow, a drop-down list with the ability to select a city. The Update button will send a request to the server, which in turn contacts a third-party service to determine the weather and returns the necessary information to us. We process this data and return it to the client’s browser. Where the client part of the widget intercepts information and displays it to the user.


Here we see some page where it is said that we supposedly know how to determine the weather. And we show our visitors a form so that they can be convinced that the weather can really be found out right here.

I didn't have fun with the layout of the form, that's not the purpose of the article. In the real world, of course, we would create a cute shape that would attract attention.

So let's go back. People check the weather, perhaps without even realizing that they are actually using another service. But everyone is satisfied and happy, you get visitors to your site, clients - the necessary information.

A little clarification is needed here: the point of widgets is to provide unique, convenient, interesting functionality. We are not giving any special information in our example. You can check the weather anywhere. But for educational purposes, since we don’t know how to do anything ourselves yet, we’ll take weather data from the Weather Forecast in Russia and the CIS service. They kindly provide a free API, which we will use.

By technology

Nothing complicated either. I already let it slip about iframe. We will write javascript code in vanillaJS, without a single additional library. Even without jQuery for DOM manipulation. Our goal is also to ensure that the resulting widget is as lightweight as possible, and there is no point in dragging a bag of additional libraries into the user’s browser to make our work easier. Therefore, let's remember how to work with the DOM and send ajax requests in native javascript, and our clients will thank us. The server part is a couple of dozen lines of code in PHP.

We write code. Creating a basic page

The page on which our future widget will be located. Let's write a couple of lines of text there about how great we are in terms of our ability to predict the weather for tomorrow. This will be the index.html file - a regular html page. In the head section we will write this:

Webdevkin. Demonstration of the Weather widget

In the body section like this:

What's interesting here? We will store styles for the page (not for the widget!) in the css/style.css file. And in in the right place create iframe..html. We remove its border and the ability to scroll and set the widget’s dimensions manually. Of course, it’s more interesting to create an adaptive one, but we’ll get to that later.

Styles for the page, without any special frills:

Body ( font-family: Arial; font-size: 14px; ) .wrapper ( width: 960px; margin: 0 auto; ) .weather-widget-container ( margin: 30px 0; )

Blank for widget

The widget is a regular html document. What is the difference? First, we won’t bother with unnecessary meta tags, because search engines don’t need our widget. And secondly, we will write both styles and js code directly in the code of the html page. We need this to make the widget load as quickly as possible, and reducing the number of requests to the web server will help us with this. We will upload everything you need in one file.

In the head section we will have the following code:

In the body section:

Let's look at these blocks in more detail.

Widget markup

Temperature for tomorrow °C

Here is the usual form. On top there is a small panel where we will display the temperature. Next select with the choice of city. Values for cities they were taken from the meteoservice.ru service, I’ll tell you where exactly later, in the section where we will directly receive weather data. And at the end there is an Update button. We will have the layout done in classes; ID numbers will be assigned to those elements that need access from javascript code. The prefix wbd- (from webdevkin) is used for convenience, so as not to confuse the markup of the widget and the main page.

Widget styles

html, body, body * ( margin: 0; padding: 0; ) .wbd-widget, .wbd-widget * ( box-sizing: border-box; font-family: Ubuntu; ) .wbd-widget ( border: solid 1px #333; padding: 20px; color: black; ) .wbd-widget__info ( color: steelblue; font-size: 16px; text-align: center; ) .wbd-widget__form-label ( display: block; line-height: 30px; )

The styles for the widget are as simple as possible - you can write them to suit yourself, however you like. Don’t forget that we put the styles directly in the widget’s html file in the head - style section.

widget javascript code.

Let's write a class that will have methods for initialization, event binding, and receiving data from the server. Don’t forget that we will write the code in native js, since we don’t want to burden users with an unnecessary load of libraries.

Var WeatherWidget = (function() ( // To perform ajax requests var XHR = ("onload" in new XMLHttpRequest()) ? XMLHttpRequest: XDomainRequest; // Widget constructor function Widget() ( this..php"; this. ui = ( updateBtn: null, citySelect: null, temperatureSpan: null ); this.init(); ) // Update weather data Widget.prototype._updateData = function(e) ( // Send an ajax request to the server ) / / Initializing ui components Widget.prototype._initUI = function() ( this.ui.updateBtn = document.getElementById("wbd-widget-update"); this.ui.citySelect = document.getElementById("wbd-widget-city" ); this.ui.temperatureSpan = document.getElementById("wbd-widget-temperature"); ) // Event binding Widget.prototype._bindHandlers = function() ( this.ui.updateBtn.addEventListener("click", Widget. prototype._updateData.bind(this)); ) // Initialize the widget Widget.prototype.init = function() ( this._initUI(); this._bindHandlers(); this._updateData(); ) // Return the widget class return Widget; ))(); new WeatherWidget();

What's going on here? We create a module based on the WeatherWidget closure, inside it we write the Widget class, into the prototype of which we add the necessary methods and return it from the closure. The last line we create an instance of the widget - new WeatherWidget();

The XHR variable is needed to perform ajax requests. In the constructor, we initialize the url property, from which we will receive weather data. There is also a ui object that stores 3 fields - the very DOM elements that we need access to from js code. They are initialized later, in the _initUI() method. The init() method causes the ui to be initialized, events to be bound, and data to be updated from the server (we want the user to immediately see the weather when rendering the widget without clicking Refresh). In _bindHandlers, the _updateData method is bound to a click on the Update button. This is the only "interactive" part of our widget.

Pay attention to the construction Widget.prototype._updateData.bind(this). Here we explicitly bind the context - we need this to always point to an instance of the Widget class in the _updateData method. Now it will be clear why - let's look at the code of the _updateData method

Receiving data from the server, _updateData method

// Update weather data Widget.prototype._updateData = function(e) ( e && e.preventDefault(); var xhr = new XHR(), city = this.ui.citySelect.value, temperatureSpan = this.ui.temperatureSpan , data = "city=" + city, resp; xhr.open("POST", this.url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(data); xhr.onreadystatechange = function() ( if (this.readyState != 4) return; if (this.status != 200) ( console.log("Request error"); return; ) resp = JSON.parse(this.responseText); temperatureSpan.innerHTML = resp.temperature; ) )

Please note that we pass the e (event) property to the method parameters. It is needed to make preventDefault at the very beginning, so as not to reload our widget (otherwise the form submit will work).
But we do it with this line
e && e.preventDefault();
This additional check for the presence of the e parameter is necessary because when we call this._updateData(), the e parameter will be undefined, and accordingly e.preventDefault() will throw an exception.

After this, we create the necessary variables, an object for the Ajax request, the selected city and a DOM element into which we display the temperature value received from the server. data will be sent in an ajax request, resp is the response from the server. Next we open the connection and send data to the server. We wait for a response of 200 from the server and display the resulting temperature in span. Let's agree that a json string comes from the server in the format ("code": "success", "temperature": "temperature range"). Traditionally, I will leave error handling to your conscience; everyone does it differently. Finally, we need to find out how to get weather data from our server.

How to find out the weather?

I recommend using this service with caution. When the article was almost ready, the format of the response to a request about the weather suddenly changed. The output of the forecast by time of day, which I initially wanted to demonstrate in the widget, was cut off. I had to partially rewrite the code and reduce the functionality of the widget, which did not make me happy. I don’t know how often such things happen with them, but using the service in real application I do not advise.

Writing php code to get weather information

It’s already clear how to take the data, the algorithm is simple: we pull out the city parameter from $_POST - the selected city, and create a string like http://xml.meteoservice.ru/export/gismeteo/point/$cityId.xml. This is the path to the weather file. We send a get request to it using curl. We parse the received response and extract the necessary parameters from it: minimum and maximum temperatures. We send the resulting numbers in a json object back to the browser.

$cityId = (int)$_POST["city"]; $url = "http://xml.meteoservice.ru/export/gismeteo/point/$cityId.xml"; $temperature = ""; if ($curl = curl_init()) ( curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); curl_close($curl); $xml = simplexml_load_string ($result); $object = $xml->REPORT->TOWN->FORECAST->TEMPERATURE; $temperature = $object["min"] . "-" . $object["max"]; ) echo json_encode( array("code" => "success", "temperature" => $temperature));

Let me explain about simplexml_load_string - this function creates an xml object that we can already parse. And an object is created from the xml string that we receive from the weather service.
REPORT->TOWN->FORECAST->TEMPERATURE - this is the path through the xml nodes to get to the desired temperature values. Follow the link above (Moscow weather) and you will clearly see these paths.
If something is unclear, ask in the comments.

Total

And that is all! We have created a simple widget for obtaining weather information. Its main feature is that it is very easy to embed on any website, you just need to insert the following lines into the html code

I believe that there are many options for using such widgets, from collecting various information to advertising banners. Do you have any ideas where this can be applied? Share in the comments!