Доброго времени суток.
Это не готовый адон, а только общее направление для написания своего адона-виджента.
Ибо выкладываемые решения ограничены некоторыми условиями, как, например, обязательное включение в плагине WP-Recall адонов
и
Результат всех действий:
Материалы по теме:
***
Итак, STEP 1 - создаем структуру адона:
(DIR) user-statistic |_(DIR) css |_(FILE) style.css |_(DIR) js |_(FILE) stat.js |_(FILE) index.php |_(FILE) info.txt
P.S. Если не предполагается как-то кастомизировать сам виджет, то директории css и js (как и вложенные файлы) - не обязательны.
В файле info.txt вставляем информацию о нашем адоне:
Name: User statistic (Статистика активности пользователей); Version: 1.0.0; Description: Supplement for Wp-Recall, show statistical analysis of user activity.; Support Core: 15.0.0; Author: Myname; Author Uri: http://mysite.com/; Add-on Uri: http://codeseller.ru/products/addon-page;
STEP 2 - создаем структуру своего виджета и активируем его
В файл index.php вставляем разметку наших будущих функций:
<?php
/**
* [myaddon_stat_dashboard_widgets Add statistic widget dashboard to $meta_boxes]
* @return [array] [All dashboard]
*/
function myaddon_stat_dashboard_widgets() {
// тут мы подключаем виджет к Wordpress
}
add_action('wp_dashboard_setup', 'myaddon_stat_dashboard_widgets' );
/**
* [myaddon_stat_dashboard_widget_show Generated statistics widget block]
* @return [string] [Prints HTML widget code]
*/
function myaddon_stat_dashboard_widget_show() {
// тут мы формируем HTML структуру виджета
}
/**
* [myaddon_stat_dashboard_widget_handle Get statistic data]
* @return [array] [Processed statistics data]
*/
function myaddon_stat_dashboard_widget_handle() {
// тут мы получаем необходимые данные для вывода в виджет
}
/**
* [myaddon_stat_scripts Add CSS and JS add-on files to back-office]
*/
function myaddon_stat_scripts() {
// тут мы подключаем кастомные стили и javascript
}
add_action( 'admin_enqueue_scripts', 'myaddon_stat_scripts' );
STEP 3 - формируем HTML структуру (функция myaddon_stat_dashboard_widget_show)
У нас есть два типа профилей наших пользователей. Условно "клиент" и "магазин".
Поэтому данные будем получать и выводить для двух групп.
итак, в предыдущем коде меням строку "// тут мы формируем HTML структуру виджета" на код:
// Display widget
$statistics_chat = myaddon_stat_dashboard_widget_handle(); // эта функция будет нам возвращать массив с данными, полученными из БД
if( !is_array( $statistics_chat ) ) {
return;
}
foreach ($statistics_chat as $key => $value) {
if ( is_array( $value ) ) {
$table .= ' <tr>
<th>' . ucfirst( __( $key ) ) . ':</th>
<th class="th-center"><span class="blue-stat">' . $value['client'] . '</span></th>
<th class="th-center"><span class="blue-stat">' . $value['shop'] . '</span></th>
</tr>';
}
}
$output = '
<table width="100%" class="widefat table-stats">
<tbody>
<tr>
<th>' . __( 'Активные чаты' ) . ':</th>
<th colspan="2"">
<span class="blue-stat">' . $statistics_chat['active'] . '</span>
</th>
</tr>
<tr>
<th width="60%"></th>
<th class="th-center">' . __( 'Клиенты' ) . '</th>
<th class="th-center">' . __( 'Магазины') . '</th>
</tr>'
. $table .
'</tbody>
</table>';
echo ' <div id="statistic_widget">
<label style="background:#ccc;">' . $output . '</label>
</div>';
STEP 4 - получаем нужные данные из БД (функция myaddon_stat_dashboard_widget_handle)
Пару слов о логике.
Данные из БД можно плучить как одним запросом, а потом разобрать их PHP интерпретатором, так и поэтапно получать несколькими запросами конкретные данные.
Я пошел вторым путем - сформировал для каждого блока свой SQL запрос. Хоть это и противоречит чувству прекрасного программиста 🙂 Но данный подход позволит в дальнейшем (если потребуется) маштабировать вывод данных в виджете. Например администратору показывать всю статистику, а редактору - только текущую и за сутки...
Меняем строку "// тут мы получаем необходимые данные для вывода в виджет" на код:
global $wpdb, $rcl_options;
$statistics_chat = array(
'active' => 0,
'today' => array(
'client' => 0,
'shop' => 0
),
'yesterday' => array(
'client' => 0,
'shop' => 0
),
'week' => array(
'client' => 0,
'shop' => 0
),
'month' => array(
'client' => 0,
'shop' => 0
),
'year' => array(
'client' => 0,
'shop' => 0
),
'total' => array(
'client' => 0,
'shop' => 0
)
);
$user_type = 'tip_polzovatelya'; // указать свой MetaKey поля профиля
// Get today statistic
$today_chat = $wpdb->get_results( "SELECT user_id FROM " . RCL_PREF . "chat_messages WHERE message_time >= CURDATE()" );
// Add time statistic to array (today)
if ( is_array( $today_chat ) ) {
$chat_s_id = array();
$chat_c_id = array();
foreach ( $today_chat as $key => $value ) {
$role = get_user_meta( $value->user_id, $user_type, 1 );
if ( $role == 'магазин' ) {
if( !in_array( $value->user_id, $chat_s_id ) ) {
$chat_s_id[] = $value->user_id;
$statistics_chat['today']['shop']++;
}
} elseif ( $role != 'магазин' ) {
if( !in_array( $value->user_id, $chat_c_id ) ) {
$chat_c_id[] = $value->user_id;
$statistics_chat['today']['client']++;
}
}
}
unset( $chat_s_id, $chat_c_id );
}
// Get yesterday statistic
$yesterday_chat = $wpdb->get_results( "SELECT user_id FROM " . RCL_PREF . "chat_messages WHERE message_time >= (CURDATE()-1) AND message_time < CURDATE()" );
// Add time statistic to array (yesterday)
if ( is_array( $yesterday_chat ) ) {
$chat_s_id = array();
$chat_c_id = array();
foreach ( $yesterday_chat as $key => $value ) {
$role = get_user_meta( $value->user_id, $user_type, 1 );
if ( $role == 'магазин' ) {
if( !in_array( $value->user_id, $chat_s_id ) ) {
$chat_s_id[] = $value->user_id;
$statistics_chat['yesterday']['shop']++;
}
} elseif ( $role != 'магазин' ) {
if( !in_array( $value->user_id, $chat_c_id ) ) {
$chat_c_id[] = $value->user_id;
$statistics_chat['yesterday']['client']++;
}
}
}
unset( $chat_s_id, $chat_c_id );
}
// Get week statistic
$week_chat = $wpdb->get_results( "SELECT user_id FROM " . RCL_PREF . "chat_messages WHERE message_time >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY)" );
// Add time statistic to array (week)
if ( is_array( $week_chat ) ) {
$chat_s_id = array();
$chat_c_id = array();
foreach ( $week_chat as $key => $value ) {
$role = get_user_meta( $value->user_id, $user_type, 1 );
if ( $role == 'магазин' ) {
if( !in_array( $value->user_id, $chat_s_id ) ) {
$chat_s_id[] = $value->user_id;
$statistics_chat['week']['shop']++;
}
} elseif ( $role != 'магазин' ) {
if( !in_array( $value->user_id, $chat_c_id ) ) {
$chat_c_id[] = $value->user_id;
$statistics_chat['week']['client']++;
}
}
}
unset( $chat_s_id, $chat_c_id );
}
// Get month statistic
$month_chat = $wpdb->get_results( "SELECT user_id FROM " . RCL_PREF . "chat_messages WHERE message_time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)" );
// Add time statistic to array (month)
if ( is_array( $month_chat ) ) {
$chat_s_id = array();
$chat_c_id = array();
foreach ( $month_chat as $key => $value ) {
$role = get_user_meta( $value->user_id, $user_type, 1 );
if ( $role == 'магазин' ) {
if( !in_array( $value->user_id, $chat_s_id ) ) {
$chat_s_id[] = $value->user_id;
$statistics_chat['month']['shop']++;
}
} elseif ( $role != 'магазин' ) {
if( !in_array( $value->user_id, $chat_c_id ) ) {
$chat_c_id[] = $value->user_id;
$statistics_chat['month']['client']++;
}
}
}
unset( $chat_s_id, $chat_c_id );
}
// Get year statistic
$year_chat = $wpdb->get_results( "SELECT user_id FROM " . RCL_PREF . "chat_messages WHERE message_time >= DATE_SUB(CURRENT_DATE, INTERVAL 1 YEAR)" );
// Add time statistic to array (year)
if ( is_array( $year_chat ) ) {
$chat_s_id = array();
$chat_c_id = array();
foreach ( $year_chat as $key => $value ) {
$role = get_user_meta( $value->user_id, $user_type, 1 );
if ( $role == 'магазин' ) {
if( !in_array( $value->user_id, $chat_s_id ) ) {
$chat_s_id[] = $value->user_id;
$statistics_chat['year']['shop']++;
}
} elseif ( $role != 'магазин' ) {
if( !in_array( $value->user_id, $chat_c_id ) ) {
$chat_c_id[] = $value->user_id;
$statistics_chat['year']['client']++;
}
}
}
unset( $chat_s_id, $chat_c_id );
}
// Get total statistic
$total_chat = $wpdb->get_results( "SELECT user_id FROM " . RCL_PREF . "chat_messages" );
// Add total statistic to array
if ( is_array( $total_chat ) ) {
$chat_s_id = array();
$chat_c_id = array();
foreach ( $year_chat as $key => $value ) {
$role = get_user_meta( $value->user_id, $user_type, 1 );
if ( $role == 'магазин' ) {
if( !in_array( $value->user_id, $chat_s_id ) ) {
$chat_s_id[] = $value->user_id;
$statistics_chat['total']['shop']++;
}
} elseif ( $role != 'магазин' ) {
if( !in_array( $value->user_id, $chat_c_id ) ) {
$chat_c_id[] = $value->user_id;
$statistics_chat['total']['client']++;
}
}
}
unset( $chat_s_id, $chat_c_id );
}
// Get active chats
if ( $rcl_options['inactivity'] ) {
$stop_time = $rcl_options['inactivity'];
} else {
$stop_time = 10;
}
$active_chat = $wpdb->get_results( "SELECT chat_id FROM " . RCL_PREF . "chat_messages WHERE message_time >= DATE_SUB(NOW() , INTERVAL " . $stop_time . " MINUTE)" );
// Add active chats to array
if ( is_array( $active_chat ) ) {
$chat_id = array();
foreach ( $active_chat as $key => $value ) {
if( !in_array( $value->chat_id, $chat_id ) ) {
$chat_id[] = $value->chat_id;
$statistics_chat['active']++;
}
}
}
return $statistics_chat;
P.S. В общем данный кусок кода можно существенно оптимизировать, например - вынести скрипт разбора массива в отдельную функцию, но, думаю, с этим справится любой. Ведь как я уже писал - это не готовое решение, а только указатель направления.
STEP 5 - подключаем виджет к Wordpress (функция myaddon_stat_dashboard_widgets)
Меняем строку "// тут мы подключаем виджет к Wordpress" на код:
wp_add_dashboard_widget(
'myaddon_stat_dashboard_widget',
__( 'Статистика чатов' ),
'myaddon_stat_dashboard_widget_show'
);
// Move widget statistics at the beginning of array
global $wp_meta_boxes;
$normal_dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
$base_widget_backup = array( 'myaddon_stat_dashboard_widget' => $normal_dashboard['myaddon_stat_dashboard_widget'] );
unset( $normal_dashboard['myaddon_stat_dashboard_widget'] );
$sorted_dashboard = array_merge( $base_widget_backup, $normal_dashboard );
$wp_meta_boxes['dashboard']['normal']['core'] = $sorted_dashboard;
Тут в принципе используется штатный функционал Wordpress, поэтому всю информацию можно получить на кодексе 🙂
И осталось подключить кастомные стили и JavaScript - если будете кастомизировать виджет 🙂
Меняем строку "// тут мы подключаем кастомные стили и javascript" на код:
wp_enqueue_style( 'rcl-stat-css', rcl_addon_url( 'css/style.css', __FILE__ ) );
wp_enqueue_script( 'rcl-stat-js', rcl_addon_url( 'js/stat.js', __FILE__ ) );
Все, результат на скрине в первом посте.
Удачного кодинга всем 🙂