wp_ajax_get_community_events

函数
wp_ajax_get_community_events ( No parameters )

wp_ajax_get_community_events函数是一个WordPress的AJAX动作,它从WordPress的事件API中检索最新的事件并以HTML格式返回: 这个函数被用来在一个小工具或网站的其他部分显示即将发生的WordPress事件: 该函数首先检查当前用户是否有查看事件的必要权限,然后使用wp_remote_get函数向WordPress事件API发出请求。然后将检索到的事件格式化为HTML,并在AJAX请求的响应中返回。

处理社区活动的Ajax请求。

function wp_ajax_get_community_events() {
	require_once ABSPATH . 'wp-admin/includes/class-wp-community-events.php';

	check_ajax_referer( 'community_events' );

	$search         = isset( $_POST['location'] ) ? wp_unslash( $_POST['location'] ) : '';
	$timezone       = isset( $_POST['timezone'] ) ? wp_unslash( $_POST['timezone'] ) : '';
	$user_id        = get_current_user_id();
	$saved_location = get_user_option( 'community-events-location', $user_id );
	$events_client  = new WP_Community_Events( $user_id, $saved_location );
	$events         = $events_client->get_events( $search, $timezone );
	$ip_changed     = false;

	if ( is_wp_error( $events ) ) {
		wp_send_json_error(
			array(
				'error' => $events->get_error_message(),
			)
		);
	} else {
		if ( empty( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) ) {
			$ip_changed = true;
		} elseif ( isset( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) && $saved_location['ip'] !== $events['location']['ip'] ) {
			$ip_changed = true;
		}

		/*
		 * The location should only be updated when it changes. The API doesn't always return
		 * a full location; sometimes it's missing the description or country. The location
		 * that was saved during the initial request is known to be good and complete, though.
		 * It should be left intact until the user explicitly changes it (either by manually
		 * searching for a new location, or by changing their IP address).
		 *
		 * If the location was updated with an incomplete response from the API, then it could
		 * break assumptions that the UI makes (e.g., that there will always be a description
		 * that corresponds to a latitude/longitude location).
		 *
		 * The location is stored network-wide, so that the user doesn't have to set it on each site.
		 */
		if ( $ip_changed || $search ) {
			update_user_meta( $user_id, 'community-events-location', $events['location'] );
		}

		wp_send_json_success( $events );
	}
}

常见问题

FAQs
查看更多 >