'GET', 'callback' => 'wavind_rest_search_spots', 'permission_callback' => function () { return current_user_can( 'edit_posts' ); }, 'args' => array( 'query' => array( 'type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } function wavind_rest_search_spots( WP_REST_Request $request ) { $query = trim( (string) $request->get_param( 'query' ) ); if ( mb_strlen( $query ) < 2 ) { return rest_ensure_response( array() ); } $query = mb_substr( $query, 0, 100 ); $cache_key = 'wavind_spots_' . md5( strtolower( $query ) ); $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return rest_ensure_response( $cached ); } $url = add_query_arg( array( 'query' => rawurlencode( $query ), 'officialOnly' => 'true', 'includePlaces' => 'false', ), wavind_api_origin() . '/spots/search' ); $response = wp_remote_get( $url, array( 'timeout' => 8 ) ); if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { return new WP_Error( 'wavind_search_failed', __( 'Wavind spot search is unavailable. Try again in a moment.', 'wavind' ), array( 'status' => 502 ) ); } $body = json_decode( wp_remote_retrieve_body( $response ), true ); $spots = array(); foreach ( isset( $body['spots'] ) && is_array( $body['spots'] ) ? $body['spots'] : array() as $spot ) { if ( empty( $spot['id'] ) || empty( $spot['name'] ) ) { continue; } $param = wavind_parse_spot_param( ( empty( $spot['slug'] ) ? '' : $spot['slug'] . '--' ) . $spot['id'] ); if ( '' === $param ) { continue; } $place = array_filter( array( isset( $spot['location']['city'] ) ? $spot['location']['city'] : '', isset( $spot['location']['country'] ) ? $spot['location']['country'] : '', ) ); $spots[] = array( 'spot' => $param, 'name' => sanitize_text_field( $spot['name'] ), 'place' => sanitize_text_field( implode( ', ', $place ) ), ); if ( count( $spots ) >= 10 ) { break; } } set_transient( $cache_key, $spots, DAY_IN_SECONDS ); return rest_ensure_response( $spots ); }