wp_localize_community_events()
云策文档标注
概述
wp_localize_community_events() 函数用于本地化社区事件数据,以便传递给 dashboard.js 脚本。它检查 dashboard 脚本是否已入队,管理用户位置基于 IP 地址的更新,并生成包含 nonce、缓存事件和时间格式的本地化数据。
关键要点
- 函数仅在 dashboard 脚本已入队时执行,否则直接返回。
- 使用 WP_Community_Events 类处理社区事件数据,包括用户位置和 IP 地址管理。
- 当用户 IP 地址变化时,自动更新保存的位置信息,确保事件显示基于当前位置。
- 通过 wp_localize_script() 将数据(如 nonce、缓存事件、时间格式)本地化到 dashboard 脚本的 communityEventsData 对象中。
代码示例
function wp_localize_community_events() {
if ( ! wp_script_is( 'dashboard' ) ) {
return;
}
require_once ABSPATH . 'wp-admin/includes/class-wp-community-events.php';
$user_id = get_current_user_id();
$saved_location = get_user_option( 'community-events-location', $user_id );
$saved_ip_address = isset( $saved_location['ip'] ) ? $saved_location['ip'] : false;
$current_ip_address = WP_Community_Events::get_unsafe_client_ip();
if ( $saved_ip_address && $current_ip_address && $current_ip_address !== $saved_ip_address ) {
$saved_location['ip'] = $current_ip_address;
update_user_meta( $user_id, 'community-events-location', $saved_location );
}
$events_client = new WP_Community_Events( $user_id, $saved_location );
wp_localize_script(
'dashboard',
'communityEventsData',
array(
'nonce' => wp_create_nonce( 'community_events' ),
'cache' => $events_client->get_cached_events(),
'time_format' => get_option( 'time_format' ),
)
);
}注意事项
- 函数依赖于 WP_Community_Events 类,需确保相关文件已加载。
- IP 地址更新逻辑仅当保存的 IP 存在且与当前 IP 不同时触发,避免不必要的用户元数据更新。
- 本地化数据包括安全 nonce,用于验证社区事件相关请求。
原文内容
Localizes community events data that needs to be passed to dashboard.js.
Source
function wp_localize_community_events() {
if ( ! wp_script_is( 'dashboard' ) ) {
return;
}
require_once ABSPATH . 'wp-admin/includes/class-wp-community-events.php';
$user_id = get_current_user_id();
$saved_location = get_user_option( 'community-events-location', $user_id );
$saved_ip_address = isset( $saved_location['ip'] ) ? $saved_location['ip'] : false;
$current_ip_address = WP_Community_Events::get_unsafe_client_ip();
/*
* If the user's location is based on their IP address, then update their
* location when their IP address changes. This allows them to see events
* in their current city when travelling. Otherwise, they would always be
* shown events in the city where they were when they first loaded the
* Dashboard, which could have been months or years ago.
*/
if ( $saved_ip_address && $current_ip_address && $current_ip_address !== $saved_ip_address ) {
$saved_location['ip'] = $current_ip_address;
update_user_meta( $user_id, 'community-events-location', $saved_location );
}
$events_client = new WP_Community_Events( $user_id, $saved_location );
wp_localize_script(
'dashboard',
'communityEventsData',
array(
'nonce' => wp_create_nonce( 'community_events' ),
'cache' => $events_client->get_cached_events(),
'time_format' => get_option( 'time_format' ),
)
);
}
Changelog
| Version | Description |
|---|---|
| 4.8.0 | Introduced. |