* Administration API: Core Ajax handlers
* @subpackage Administration
// No-privilege Ajax handlers.
* Ajax handler for the Heartbeat API in the no-privilege context.
* Runs when the user is not logged in.
function wp_ajax_nopriv_heartbeat() {
// 'screen_id' is the same as $current_screen->id and the JS global 'pagenow'.
if ( ! empty( $_POST['screen_id'] ) ) {
$screen_id = sanitize_key( $_POST['screen_id'] );
if ( ! empty( $_POST['data'] ) ) {
$data = wp_unslash( (array) $_POST['data'] );
* Filters Heartbeat Ajax response in no-privilege environments.
* @param array $response The no-priv Heartbeat response.
* @param array $data The $_POST data sent.
* @param string $screen_id The screen ID.
$response = apply_filters( 'heartbeat_nopriv_received', $response, $data, $screen_id );
* Filters Heartbeat Ajax response in no-privilege environments when no data is passed.
* @param array $response The no-priv Heartbeat response.
* @param string $screen_id The screen ID.
$response = apply_filters( 'heartbeat_nopriv_send', $response, $screen_id );
* Fires when Heartbeat ticks in no-privilege environments.
* Allows the transport to be easily replaced with long-polling.
* @param array $response The no-priv Heartbeat response.
* @param string $screen_id The screen ID.
do_action( 'heartbeat_nopriv_tick', $response, $screen_id );
// Send the current time according to the server.
$response['server_time'] = time();
wp_send_json( $response );
// GET-based Ajax handlers.
* Ajax handler for fetching a list table.
function wp_ajax_fetch_list() {
$list_class = $_GET['list_args']['class'];
check_ajax_referer( "fetch-list-$list_class", '_ajax_fetch_list_nonce' );
$wp_list_table = _get_list_table( $list_class, array( 'screen' => $_GET['list_args']['screen']['id'] ) );
if ( ! $wp_list_table ) {
if ( ! $wp_list_table->ajax_user_can() ) {
$wp_list_table->ajax_response();
* Ajax handler for tag search.
function wp_ajax_ajax_tag_search() {
if ( ! isset( $_GET['tax'] ) ) {
$taxonomy = sanitize_key( $_GET['tax'] );
$tax = get_taxonomy( $taxonomy );
if ( ! current_user_can( $tax->cap->assign_terms ) ) {
$s = wp_unslash( $_GET['q'] );
$comma = _x( ',', 'tag delimiter' );
$s = str_replace( $comma, ',', $s );
if ( false !== strpos( $s, ',' ) ) {
$s = $s[ count( $s ) - 1 ];
* Filters the minimum number of characters required to fire a tag search via Ajax.
* @param int $characters The minimum number of characters required. Default 2.
* @param WP_Taxonomy $tax The taxonomy object.
* @param string $s The search term.
$term_search_min_chars = (int) apply_filters( 'term_search_min_chars', 2, $tax, $s );
* Require $term_search_min_chars chars for matching (default: 2)
* ensure it's a non-negative, non-zero integer.
if ( ( 0 == $term_search_min_chars ) || ( strlen( $s ) < $term_search_min_chars ) ) {
echo implode( "\n", $results );
* Ajax handler for compression testing.
function wp_ajax_wp_compression_test() {
if ( ! current_user_can( 'manage_options' ) ) {
if ( ini_get( 'zlib.output_compression' ) || 'ob_gzhandler' === ini_get( 'output_handler' ) ) {
update_site_option( 'can_compress_scripts', 0 );
if ( isset( $_GET['test'] ) ) {
header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
header( 'Content-Type: application/javascript; charset=UTF-8' );
$force_gzip = ( defined( 'ENFORCE_GZIP' ) && ENFORCE_GZIP );
$test_str = '"wpCompressionTest Lorem ipsum dolor sit amet consectetuer mollis sapien urna ut a. Eu nonummy condimentum fringilla tempor pretium platea vel nibh netus Maecenas. Hac molestie amet justo quis pellentesque est ultrices interdum nibh Morbi. Cras mattis pretium Phasellus ante ipsum ipsum ut sociis Suspendisse Lorem. Ante et non molestie. Porta urna Vestibulum egestas id congue nibh eu risus gravida sit. Ac augue auctor Ut et non a elit massa id sodales. Elit eu Nulla at nibh adipiscing mattis lacus mauris at tempus. Netus nibh quis suscipit nec feugiat eget sed lorem et urna. Pellentesque lacus at ut massa consectetuer ligula ut auctor semper Pellentesque. Ut metus massa nibh quam Curabitur molestie nec mauris congue. Volutpat molestie elit justo facilisis neque ac risus Ut nascetur tristique. Vitae sit lorem tellus et quis Phasellus lacus tincidunt nunc Fusce. Pharetra wisi Suspendisse mus sagittis libero lacinia Integer consequat ac Phasellus. Et urna ac cursus tortor aliquam Aliquam amet tellus volutpat Vestibulum. Justo interdum condimentum In augue congue tellus sollicitudin Quisque quis nibh."';
if ( 1 == $_GET['test'] ) {
} elseif ( 2 == $_GET['test'] ) {
if ( ! isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
if ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate' ) && function_exists( 'gzdeflate' ) && ! $force_gzip ) {
header( 'Content-Encoding: deflate' );
$out = gzdeflate( $test_str, 1 );
} elseif ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) && function_exists( 'gzencode' ) ) {
header( 'Content-Encoding: gzip' );
$out = gzencode( $test_str, 1 );
} elseif ( 'no' === $_GET['test'] ) {
check_ajax_referer( 'update_can_compress_scripts' );
update_site_option( 'can_compress_scripts', 0 );
} elseif ( 'yes' === $_GET['test'] ) {
check_ajax_referer( 'update_can_compress_scripts' );
update_site_option( 'can_compress_scripts', 1 );
* Ajax handler for image editor previews.
function wp_ajax_imgedit_preview() {
$post_id = (int) $_GET['postid'];
if ( empty( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
check_ajax_referer( "image_editor-$post_id" );
include_once ABSPATH . 'wp-admin/includes/image-edit.php';
if ( ! stream_preview_image( $post_id ) ) {
* Ajax handler for oEmbed caching.
* @global WP_Embed $wp_embed
function wp_ajax_oembed_cache() {
$GLOBALS['wp_embed']->cache_oembed( $_GET['post'] );
* Ajax handler for user autocomplete.
function wp_ajax_autocomplete_user() {
if ( ! is_multisite() || ! current_user_can( 'promote_users' ) || wp_is_large_network( 'users' ) ) {
/** This filter is documented in wp-admin/user-new.php */
if ( ! current_user_can( 'manage_network_users' ) && ! apply_filters( 'autocomplete_users_for_site_admins', false ) ) {
// Check the type of request.
// Current allowed values are `add` and `search`.
if ( isset( $_REQUEST['autocomplete_type'] ) && 'search' === $_REQUEST['autocomplete_type'] ) {
$type = $_REQUEST['autocomplete_type'];
// Check the desired field for value.
// Current allowed values are `user_email` and `user_login`.
if ( isset( $_REQUEST['autocomplete_field'] ) && 'user_email' === $_REQUEST['autocomplete_field'] ) {
$field = $_REQUEST['autocomplete_field'];
// Exclude current users of this blog.
if ( isset( $_REQUEST['site_id'] ) ) {
$id = absint( $_REQUEST['site_id'] );
$id = get_current_blog_id();
$include_blog_users = ( 'search' === $type ? get_users(
$exclude_blog_users = ( 'add' === $type ? get_users(
'search' => '*' . $_REQUEST['term'] . '*',
'include' => $include_blog_users,
'exclude' => $exclude_blog_users,
'search_columns' => array( 'user_login', 'user_nicename', 'user_email' ),
foreach ( $users as $user ) {
/* translators: 1: User login, 2: User email address. */
'label' => sprintf( _x( '%1$s (%2$s)', 'user autocomplete result' ), $user->user_login, $user->user_email ),
'value' => $user->$field,
wp_die( wp_json_encode( $return ) );
* Handles Ajax requests for community events
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 );
if ( is_wp_error( $events ) ) {
'error' => $events->get_error_message(),
if ( empty( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) ) {
} elseif ( isset( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) && $saved_location['ip'] !== $events['location']['ip'] ) {
* 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_option( $user_id, 'community-events-location', $events['location'], true );
wp_send_json_success( $events );
* Ajax handler for dashboard widgets.
function wp_ajax_dashboard_widgets() {
require_once ABSPATH . 'wp-admin/includes/dashboard.php';
$pagenow = $_GET['pagenow'];
if ( 'dashboard-user' === $pagenow || 'dashboard-network' === $pagenow || 'dashboard' === $pagenow ) {
set_current_screen( $pagenow );
switch ( $_GET['widget'] ) {
case 'dashboard_primary':
* Ajax handler for Customizer preview logged-in status.
function wp_ajax_logged_in() {
* Sends back current comment total and new page links if they need to be updated.
* Contrary to normal success Ajax response ("1"), die with time() on success.
function _wp_ajax_delete_comment_response( $comment_id, $delta = -1 ) {
$total = isset( $_POST['_total'] ) ? (int) $_POST['_total'] : 0;
$per_page = isset( $_POST['_per_page'] ) ? (int) $_POST['_per_page'] : 0;
$page = isset( $_POST['_page'] ) ? (int) $_POST['_page'] : 0;
$url = isset( $_POST['_url'] ) ? esc_url_raw( $_POST['_url'] ) : '';
// JS didn't send us everything we need to know. Just die with success message.
if ( ! $total || ! $per_page || ! $page || ! $url ) {
$comment = get_comment( $comment_id );
$comment_status = $comment->comment_approved;
if ( 1 === (int) $comment_status ) {
$comment_link = get_comment_link( $comment );
$counts = wp_count_comments();
$x = new WP_Ajax_Response(
// Here for completeness - not used.
'status' => $comment_status,
'postId' => $comment ? $comment->comment_post_ID : '',
'in_moderation' => $counts->moderated,
'i18n_comments_text' => sprintf(
/* translators: %s: Number of comments. */
_n( '%s Comment', '%s Comments', $counts->approved ),
number_format_i18n( $counts->approved )
'i18n_moderation_text' => sprintf(
/* translators: %s: Number of comments. */
_n( '%s Comment in moderation', '%s Comments in moderation', $counts->moderated ),
number_format_i18n( $counts->moderated )
'comment_link' => $comment_link,
// Only do the expensive stuff on a page-break, and about 1 other time per page.
if ( 0 == $total % $per_page || 1 == mt_rand( 1, $per_page ) ) {
// What type of comment count are we looking for?
$parsed = parse_url( $url );
if ( isset( $parsed['query'] ) ) {
parse_str( $parsed['query'], $query_vars );
if ( ! empty( $query_vars['comment_status'] ) ) {
$status = $query_vars['comment_status'];
if ( ! empty( $query_vars['p'] ) ) {
$post_id = (int) $query_vars['p'];