Мне было интересно, если и как я могу встроить / отобразить некоторые параметры из wp-admin / profile.php для внешнего интерфейса.Вот случай:
Я установил плагин под названием Woocommerce Appointments, который отвечает за создание заказов.Персонал может установить собственную доступность, но может сделать это, только войдя в панель управления WordPress и, особенно, в раздел «Пользователи-> Страница вашего профиля».
Было бы идеально, если бы я мог создать виджет с кодом доступности, чтобы яможет отобразить его везде, где я хочу в передней части.
Возможно ли это? Вот код:
<code><?php
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
class WC_Appointments_Admin_Staff_Profile {
/**
* Constructor
*/
public function __construct() {
add_action( 'show_user_profile', array( $this, 'add_staff_meta_fields' ), 20 );
add_action( 'edit_user_profile', array( $this, 'add_staff_meta_fields' ), 20 );
add_action( 'personal_options_update', array( $this, 'save_staff_meta_fields' ) );
add_action( 'edit_user_profile_update', array( $this, 'save_staff_meta_fields' ) );
add_action( 'delete_user', array( $this, 'delete_staff' ), 11 );
}
/**
* Show meta box
*/
public function add_staff_meta_fields( $user ) {
if ( ! current_user_can( 'edit_user', $user->ID ) ) {
return;
}
wp_enqueue_script( 'wc_appointments_writepanel_js' );
?>
<style type="text/css">
#minor-publishing-actions, #visibility { display:none }
</style>
<h3 id="staff-gcal"><?php esc_html_e( '2-way Google Calendar Sync', 'woocommerce-appointments' ); ?></h3>
<table class="form-table">
<?php
// Calendar ID.
$calendar_id = get_user_meta( $user->ID, 'wc_appointments_gcal_calendar_id', true );
$calendar_id = $calendar_id ? $calendar_id : '';
// Run Gcal oauth redirect.
$gcal_integration_class = wc_appointments_integration_gcal();
$gcal_integration_class->set_user_id( $user->ID );
// Get access token.
$access_token = $gcal_integration_class->get_access_token();
$client_id = $gcal_integration_class->get_client_id();
$client_secret = $gcal_integration_class->get_client_secret();
$twoway = $gcal_integration_class->get_twoway();
// 2-way sync enabled?
$twoway_enabled = ( 'no' === $twoway ) ? false : true;
?>
<tr>
<th><label><?php esc_html_e( 'Authorization', 'woocommerce-appointments' ); ?></label></th>
<td>
<?php if ( ! $access_token && $client_id && $client_secret ) : ?>
<button type="button" class="button oauth_redirect" data-staff="<?php echo esc_attr( absint( $user->ID ) ); ?>" data-logout="0"><?php esc_html_e( 'Connect with Google', 'woocommerce-appointments' ); ?></button>
<?php elseif ( $access_token ) : ?>
<p><?php esc_html_e( 'Successfully authenticated.', 'woocommerce-appointments' ); ?></p>
<p class="submit">
<button type="button" class="button oauth_redirect" data-staff="<?php echo esc_attr( absint( $user->ID ) ); ?>" data-logout="1"><?php esc_html_e( 'Disconnect', 'woocommerce-appointments' ); ?></button>
</p>
<?php else : ?>
<p>
<?php
/* translators: 1: link to google calendar sync settings */
printf( __( 'Please configure <a href="%s">Google Calendar Sync settings</a> first.', 'woocommerce-appointments' ), esc_url( admin_url( 'admin.php?page=wc-settings&tab=appointments§ion=gcal' ) ) );
?>
</p>
<?php endif; ?>
</td>
</tr>
<?php if ( $access_token ) : ?>
<tr>
<th><label for="wc_appointments_gcal_calendar_id"><?php esc_html_e( 'Calendar ID', 'woocommerce-appointments' ); ?></label></th>
<td>
<?php $calendar_id = get_user_meta( $user->ID, 'wc_appointments_gcal_calendar_id', true ); ?>
<?php $calendar_id = $calendar_id ? $calendar_id : ''; ?>
<?php if ( $calendar_id ) : ?>
<input type="text" class="regular-text" name="wc_appointments_gcal_calendar_id" id="wc_appointments_gcal_calendar_id" value="<?php echo esc_attr( $calendar_id ); ?>">
<?php else : ?>
<select id="wc_appointments_gcal_calendar_id" name="wc_appointments_gcal_calendar_id" class="wc-enhanced-select" style="width:25em;">
<option value=""><?php esc_html_e( 'N/A', 'woocommerce-appointments' ); ?></option>
<?php
// Get all Google Calendars.
$get_user_calendars = $gcal_integration_class->get_user_calendars();
// Check if Authorized and calendars exist.
if ( $access_token && $get_user_calendars ) {
foreach ( $get_user_calendars as $cal_id => $cal_name ) {
?>
<option value="<?php echo esc_attr( $cal_id ); ?>" <?php selected( $calendar_id, $cal_id ); ?>><?php echo esc_attr( $cal_name ); ?></option>
<?php
}
}
?>
</select>
<?php endif; ?>
</td>
</tr>
<?php
if ( $calendar_id && $twoway_enabled ) :
?>
<tr>
<th><label><?php esc_html_e( 'Last Sync', 'woocommerce-appointments' ); ?></label></th>
<td>
<?php
#$rules = get_user_meta( $user->ID, 'wc_appointments_gcal_availability', true );
#print '<pre>'; print_r( $rules ); print '
';$ last_synced = get_user_meta ($ user-> ID, 'wc_appointments_gcal_availability_last_synced', true);$ last_synced = $ last_synced?$ last_synced: '';if ($ last_synced) {$ ls_timestamp = isset ($ last_synced [0]) && $ last_synced [0]?absint ($ last_synced [0]): absint (current_time ('timestamp')));$ ls_counter = isset ($ last_synced [1]) && $ last_synced [1]?абсент ($ last_synced [1]): 0;/ * переводчики: 1: единственное число события, 2: множественное число событий * / $ ls_message = sprintf (_n ('событие% s.', 'события% s.', $ ls_counter, 'woocommerce-назначений'), number_format_i18n ($ ls_counter));$ ls_message. = '';/ * переводчики: 1: формат даты, 2: формат времени * / $ ls_message. = sprintf (__ ('% 1 $ s,% 2 $ s', 'woocommerce-назначений'), date_i18n (wc_date_format (), $ ls_timestamp), date_i18n (wc_time_format (), $ ls_timestamp));?>
Я БЫ );$ staff_availability = $ staff-> get_availability (true);if (! empty ($ staff_availability) && is_array ($ staff_availability)) {if (! empty ($ staff_availability [0])) {foreach ($ staff_availability как $ available) {include 'views / html-meeting-Availability-fields.PHP ';}}}?>
"> get_appointable_product_ids_for_staff ($ user-> ID);$ user_product_ids_comma =!пусто ($ user_product_ids) && is_array ($ user_product_ids)?implode (',', $ user_product_ids): '';$ all_appointable_products = WC_Appointments_Admin :: get_appointment_products (true);if (! empty ($ user_product_ids) && is_array ($ user_product_ids)) {foreach ($ user_product_ids as $ user_product_id) {$ user_id = $ user-> ID;включите 'views / html-meeting-staff-fields.php';}}?> '.esc_html ($ appointable_product-> get_title ()).'';}?> $ available [$ i] ['to'] = wc_clean ($ _POST ['wc_appointment_availability_to_date'] [$ i]);перерыв;case 'months': $ Availability [$ I] ['from'] = wc_clean ($ _POST ['wc_appointment_availability_from_month'] [$ i]);$ available [$ i] ['to'] = wc_clean ($ _POST ['wc_appointment_availability_to_month'] [$ i]);перерыв;case 'days': $ наличие [$ i] ['from'] = wc_clean ($ _POST ['wc_appointment_availability_from_week'] [$ i]);$ available [$ i] ['to'] = wc_clean ($ _POST ['wc_appointment_availability_to_week'] [$ i]);перерыв;case 'days': $ Availability [$ I] ['from'] = wc_clean ($ _POST ['wc_appointment_availability_from_day_of_week'] [$ i]);$ Availability [$ I] ['to'] = wc_clean ($ _POST ['wc_appointment_availability_to_day_of_week'] [$ i]);перерыв;case 'time': case 'time: 1': case 'time: 2': case 'time: 3': case 'time: 4': case 'time: 5': case 'time: 6': case 'time: 7 ': $ available [$ i] [' from '] = wc_appointment_sanitize_time ($ _POST [' wc_appointment_availability_from_time '] [$ i]);$ available [$ i] ['to'] = wc_appointment_sanitize_time ($ _POST ['wc_appointment_availability_to_time'] [$ i]);перерыв;case 'time: range': $ Availability [$ I] ['from'] = wc_appointment_sanitize_time ($ _POST ['wc_appointment_availability_from_time'] [$ i]);$ available [$ i] ['to'] = wc_appointment_sanitize_time ($ _POST ['wc_appointment_availability_to_time'] [$ i]);$ Availability [$ I] ['from_date'] = wc_clean ($ _POST ['wc_appointment_availability_from_date'] [$ i]);$ Availability [$ I] ['to_date'] = wc_clean ($ _POST ['wc_appointment_availability_to_date'] [$ i]);перерыв;}} update_user_meta ($ user_id, '_wc_appointment_availability', $ Availability);// Назначенные продукты.$ staff_products = isset ($ _POST ['staff_product_id'])?$ _POST ['staff_product_id']: '';$ staff_base_costs = isset ($ _POST ['staff_base_costs'])?$ _POST ['staff_base_costs']: '';$ staff_qtys = isset ($ _POST ['staff_qtys'])?$ _POST ['staff_qtys']: '';if ($ staff_products &&! empty ($ staff_products)) {foreach ($ staff_products as $ staff_product_id) {$ appointable_product = new WC_Product_Appointment ($ staff_product_id);if (! is_a ($ appointable_product, 'WC_Product_Appointment')) {continue;} // Назначить персонал на продукт.$ staff_ids = $ appointable_product-> get_staff_ids ();if (! in_array ($ user_id, $ staff_ids)) {$ staff_ids [] = $ user_id;} $ appointable_product-> set_staff_ids ($ staff_ids);// Добавляем базовые затраты на персонал к продукту.$ product_staff_base_costs = $ appointable_product-> get_staff_base_costs ();$ product_staff_base_costs [$ user_id] = floatval ($ staff_base_costs [$ staff_product_id]);$ appointable_product-> set_staff_base_costs ($ product_staff_base_costs);// Добавляем базовые затраты на персонал к продукту.$ product_staff_qtys = $ appointable_product-> get_staff_qtys ();$ product_staff_qtys [$ user_id] = intval ($ staff_qtys [$ staff_product_id]);$ appointable_product-> set_staff_qtys ($ product_staff_qtys);$ Appointable_product-> Save ();}} // ID календаря.$ calendar_id = isset ($ _POST ['wc_appointments_gcal_calendar_id'])?$ _POST ['wc_appointments_gcal_calendar_id']: '';if (! $ calendar_id) {delete_user_meta ($ user_id, 'wc_appointments_gcal_calendar_id');delete_user_meta ($ user_id, 'wc_appointments_gcal_availability');delete_user_meta ($ user_id, 'wc_appointments_gcal_availability_last_synced');wp_clear_scheduled_hook ('wc-встречи-sync-from-gcal', массив ($ user_id));} else {update_user_meta ($ user_id, 'wc_appointments_gcal_calendar_id', $ calendar_id);} // Запланируем пошаговую синхронизацию каждый час.if ($ calendar_id &&! wp_next_scheduled ('wc-встречи-sync-from-gcal', массив ($ user_id))) {wp_clear_scheduled_hook ('wc-meeting-sync-from-gcal', массив ($ user_id));wp_schedule_event (time (), apply_filters ('woocommerce_appointments_sync_from_gcal', 'hourly'), 'wc-meeting-sync-from-gcal');} // Сбросить пошаговую синхронизацию каждый час.if (! $ calendar_id) {wp_clear_scheduled_hook ('wc-встречи-sync-from-gcal', массив ($ user_id));}} / ** * Действия, которые необходимо выполнить при удалении персонала * / public function delete_staff ($ user_id) {$ user_meta = get_userdata ($ user_id);// Проверка ролей, если пользователь является сотрудником магазина.if (in_array ('shop_staff', (array) $ user_meta-> role)) {// Получить все назначения сотрудников и удалить сотрудников из них.$ assignments_args = array ('meta_query' => array (array ('key' => '_appointment_staff_id', 'value' => absint ($ user_id),),), 'post_status' => get_wc_appointment_statuses ('validate'),);$ staff_appointments = WC_Appointments_Controller :: get_appointments ($ assignments_args);if (! empty ($ staff_appointments)) {foreach ($ staff_appointments as $ staff_appointment) {delete_post_meta ($ staff_appointment-> id, '_appointment_staff_id');}} // Получить все продукты, на которые назначен текущий персонал, и удалить его / ее из продукта (вернуть реляционную таблицу БД и разместить мета-логику в class-wc-assignments-admin.php в строке 559-593) $ staff_product_ids = WC_Data_Store:: нагрузка ('назначение продукта') -> get_appointable_product_ids_for_staff ($ user_id);if (! empty ($ staff_product_ids)) {foreach ($ staff_product_ids as $ staff_product_id) {WC_Data_Store :: load ('product-assignment') -> remove_staff_from_product ($ user_id, $ staff_product_id);}} // Проверка ролей, если пользователь является сотрудником магазина.} elseif (in_array ('customer', (array) $ user_meta-> role)) {$ customer_appointments_args = array ('meta_query' => array (array ('key' => '_appointment_customer_id', 'value' => absint ($ user_id), 'Compare' => 'IN',),), 'post_status' => get_wc_appointment_statuses ('user'),);$ customer_appointments = WC_Appointments_Controller :: get_appointments ($ customer_appointments_args);if (! empty ($ customer_appointments)) {foreach ($ customer_appointments as $ customer_appointment) {delete_post_meta ($ customer_appointment-> id, '_appointment_customer_id');}}}}} return new WC_Appointments_Admin_Staff_Profile ();