Console Widget Development. Widget API WordPress
If you have basic programming knowledge, then it will not be difficult for you to learn how to create your own WordPress widgets. This article will be useful to you if you are preparing to create your own WordPress plugins.. I won't pull, just start making your widgets.
Building a simple plugin
Let's create a simple plugin first., for this we need to create in the plugins folder /wp-content/plugins/ file test-plugin.php. In the created file, create the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php /** * @package Create_widget * @version 1.6 */ /* Plugin Name: Create widget Plugin URI: https://wp-admin.com.ua/widget-api-wordpress/ Description: Плагин который добавляет виджет. Author: Максим Version: 1.6 Author URI: https://wp-admin.com.ua/ */ ?> |
I will not describe the plugin lines now., think, for this it is worth devoting a separate article, but this simple code will allow us to display our plugin in the admin panel, you can activate it immediately.
This is how the plugin will look in the WordPress admin panel in the plugins section.
After activating the plugin, we can continue to add it. The main tool for adding a widget is the function wp_add_dashboard_widget () which adds a widget to the WordPress dashboard. Consider the function input:
- $widget_id (integer) – required parameter, identifier, will be used as the CSS class and key in the widgets array of the WordPress Dashboard.
- $widget_name (line) – required parameter, widget name, which will be displayed in the header of the widget.
- $callback (line) – required parameter, function name, which will display the contents of the Console widget.
- $control_callback (line) – optional parameter, callback, function name, which will handle the form of the new Console widget. For the time being, we will not work with this function..
Example and order of entering parameters for the wp_add_dashboard_widget function
1 |
<?php wp_add_dashboard_widget($widget_id, $widget_name, $callback, $control_callback ); ?> |
Widget add function code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php // Функция отображения содержимого нового виджета Консоли: function dashboard_widget_function() { echo "Hello World, this id my first Dashboard Widget!"; } // Функция, используемая в действии крючка: function add_dashboard_widgets() { wp_add_dashboard_widget('dashboard_widget', 'Example Dashboard Widget', 'dashboard_widget_function'); } // Регистрация нового виджета Консоли с помощью действия 'wp_dashboard_setup': add_action('wp_dashboard_setup', 'add_dashboard_widgets' ); ?> |
Running Widgets in the Console implements an action wp_dashboard_setup which calls the function add_dashboard_widgets. In our example, the function add_dashboard_widgets responsible for displaying information in the widget block.
As a result of using this code in our plugin, the widget will be shown in the CMS console.
Widget output example
This example can be used to output all sorts of important information to the console (online store sales statistics, contacts of the studio that developed the site and maintains it, articles that were published by users with a certain role or even by a separate user). Information can be displayed in various.
You probably noticed, that some widgets have additional settings, for example, the fresh comments widget can be configured and specify how many of them will be displayed in the console.
Let us consider in more detail the methods for implementing this functionality.. Firstly, for those who do not know in WordPress, intermediate options and parameters are saved using a special options mechanism. You can practice working with options in one of my articles called “Storing data in wordpress“.
If you are familiar with the options mechanism or you have read my articles and understood everything, then try to replace the old code of our plugin with this one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<?php /** * @package Create_widget * @version 1.6 */ /* Plugin Name: Create widget Plugin URI: https://wp-admin.com.ua/widget-api-wordpress/ Description: Плагин который добавляет виджет. Author: Максим Version: 1.6 Author URI: https://wp-admin.com.ua/ */ //Показать widget function custom_dashboard_widget_coach() { //get saved data if ( !$widget_options = get_option( 'my_dashboard_widget_options' ) ) $widget_options = array(); $saved_team = isset($widget_options['team'])? $widget_options['team'] : ''; echo " <p><strong>Выберите один из вариантов</strong></p> <div class='team_class_wrap'> <label>Выбран вариант: {$saved_team}</label> </div> "; } //Настройка и обновление widget function custom_dashboard_widget_coach_handle(){ // получить сохраненные данные if ( !$widget_options = get_option( 'my_dashboard_widget_options' ) ) $widget_options = array(); // обновление данных if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset($_POST['my_dashboard_widget_options']) ) { // базовая валидация // Чистим строку, оставляя в ней только указанные HTML теги, их атрибуты и значения атрибутов. $widget_options['team'] = wp_kses($_POST['my_dashboard_widget_options']['team'],array() ); //Сохраняем изменения в опциях update_option( 'my_dashboard_widget_options', $widget_options ); } // задаем значение по умолчанию if(!isset($widget_options['team'])) $widget_options['team'] = ''; // тут вы можите задать значение по умолчанию echo " <p><strong>Выберите один из вариантов</strong></p> <div class='team_class_wrap'> <label>Выберите параметр:</label> <select name='my_dashboard_widget_options[team]' id='team'> <option value='1' ".selected( $widget_options['team'], '1', false ).">1</option> <option value='2' ".selected( $widget_options['team'], '2', false ).">2</option> <option value='3' ".selected( $widget_options['team'], '3', false ).">3</option> <option value='4' ".selected( $widget_options['team'], '4', false ).">4</option> </select> </div> "; } // регистрация виджета function add_custom_dashboard_widget_coach() { wp_add_dashboard_widget('custom_dashboard_widget_coach', 'Пример виджета с опциями', 'custom_dashboard_widget_coach', 'custom_dashboard_widget_coach_handle'); } add_action('wp_dashboard_setup', 'add_custom_dashboard_widget_coach'); ?> |
Removing unnecessary widgets from the console
There are two approaches. The first approach is to clear the global array that contains the list of widgets like this:
1 2 3 4 5 |
function remove_dashboard_widgets() { global $wp_meta_boxes; unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']); } add_action('wp_dashboard_setup', 'remove_dashboard_widgets' ); |
This example removes the widget Quick Publication.
Other widgets can be removed if necessary, slightly changing the last nested key in the array:
Removes a widget “Plugins”
$wp_meta_boxes[‘dashboard’][‘normal’][‘core’][‘dashboard_plugins’]
Removes “Fresh drafts”
$wp_meta_boxes[‘dashboard’][‘side’][‘core’][‘dashboard_recent_drafts’]
Removes “Fresh comments”
$wp_meta_boxes[‘dashboard’][‘normal’][‘core’][‘dashboard_recent_comments’]
Removes a widget “Incoming links”
$wp_meta_boxes[‘dashboard’][‘normal’][‘core’][‘dashboard_incoming_links’]
Removes a widget “Right now”
$wp_meta_boxes[‘dashboard’][‘normal’][‘core’][‘dashboard_right_now’]
To remove all blocks of standard widgets from the WordPress Dashboard use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 |
function remove_dashboard_widgets() { global $wp_meta_boxes; unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']); unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']); unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_quick_press']); unset($wp_meta_boxes['dashboard']['side']['core']['recent_drafts']); unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_right_now']); } add_action('wp_dashboard_setup', 'remove_dashboard_widgets' ); |
Also the second approach to remove, this is the use of special functions of the CMS core. Here is an example of the WordPress Codex.
1 2 3 4 5 6 7 8 |
// Создаем функцию для использования в специальном экшене function example_remove_dashboard_widgets() { remove_meta_box( 'dashboard_quick_press', 'dashboard', 'side' ); remove_meta_box( 'dashboard_incoming_links', 'dashboard', 'normal' ); } // Экшен для запуска функции 'wp_dashboard_setup' add_action('wp_dashboard_setup', 'example_remove_dashboard_widgets' ); |
If you don't need to remove widget blocks, but your widget after installing the plugin got to the end, it can be put at the beginning by default by rearranging the global array with all widgets (global $wp_meta_boxes;). I don’t write about array sorting and rearrangement here, these are php questions.
For more advanced work with widgets, you can always see how they were programmed in the very core of WordPress., in file:
/wp-admin/includes/dashboard.php
Read more about the Widget API
Code to display all options standard widgets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function get_dashboard_widget_options( $widget_id='' ) { //Берем все опции виджетов из базы данных $opts = get_option( 'dashboard_widget_options' ); //Если не указан идентификатор виджета, то берем все опции if ( empty( $widget_id ) ) return $opts; //Если указан идентификатор виджета, то возвращаем только опции этого виджета, если таковые есть if ( isset( $opts[$widget_id] ) ) return $opts[$widget_id]; //если ни одно условие не подошло возвращаем false... return false; } |
To display one widget option you can use the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public static function get_dashboard_widget_option( $widget_id, $option, $default=NULL ) { $opts = get_dashboard_widget_options($widget_id); //если опции не найдены false if ( ! $opts ) return false; //В противном случаи, если есть опция и она не пустая, выводим содержимое опции if ( isset( $opts[$option] ) && ! empty($opts[$option]) ) return $opts[$option]; else return ( isset($default) ) ? $default : false; } |
To update widget options WordPress codex offers the following function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static function update_dashboard_widget_options( $widget_id , $args=array(), $add_only=false ) { //достаем все опции виджета из базы данных... $opts = get_option( 'dashboard_widget_options' ); //берем опции только нашего виджета или объявляем пустой массив $w_opts = ( isset( $opts[$widget_id] ) ) ? $opts[$widget_id] : array(); if ( $add_only ) { //Flesh out any missing options (existing ones overwrite new ones) $opts[$widget_id] = array_merge($args,$w_opts); } else { // Добавляем к существующим опциям новые $opts[$widget_id] = array_merge($w_opts,$args); } //Сохраняем весь массив опций виджета обратно в базу данных return update_option('dashboard_widget_options', $opts); } |
For a more complete study of the material, you may need articles:
For today, I think you will have enough material that you can study and test in your plugins. Good luck in developing quality sites.
/*
- Basic web design course;
- Site layout;
- General course on CMS WordPress and continuation of the course on template development;
- Website development in PHP.