play.wenpai.net/mu-plugins/wenpai-accelerate.php
feibisi d6064a9e9d fix: strip wp_blog/wp_install headers to resolve CORS preflight
api.wenpai.net rejects wp_blog custom header in CORS preflight,
causing Service Worker pre-fetch failures. Strip these WordPress-
specific headers before redirected requests.

v1.0.0 → v1.1.0
2026-02-20 21:38:08 +08:00

80 lines
2.2 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Plugin Name: WenPai Accelerate (Playground)
* Description: Lightweight API redirect for China — replaces wp-china-yes in WASM env.
* Version: 1.1.0
* Author: WenPai.org
* License: GPL-2.0-or-later
*
* 功能:
* 1. 将 api.wordpress.org / downloads.wordpress.org 重定向到 wenpai.net 镜像
* 2. 将 Gravatar 头像重定向到 Cravatar 国内源
* 3. 剥离 wp_blog/wp_install 自定义 header修复 WASM 环境 CORS preflight 失败)
* 4. 静默 WP_DEBUG 日志噪音Playground 环境非关键错误)
*
* 设计原则:
* - 极简实现,避免 wp-china-yes 在 WASM 环境中的兼容性问题
* - 无设置页面、无数据库写入、无外部依赖
* - 作为 mu-plugin 自动加载,无需激活
*/
// 防止直接访问
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* 重定向 WordPress.org API 请求到 WenPai.net 镜像
*
* @param false|array|\WP_Error $preempt 预处理结果
* @param array $args 请求参数
* @param string $url 请求 URL
* @return false|array|\WP_Error
*/
add_filter(
'pre_http_request',
function ( $preempt, $args, $url ) {
$host = wp_parse_url( $url, PHP_URL_HOST );
if ( ! in_array( $host, array( 'api.wordpress.org', 'downloads.wordpress.org' ), true ) ) {
return $preempt;
}
$new_url = str_replace(
array( 'api.wordpress.org', 'downloads.wordpress.org' ),
array( 'api.wenpai.net', 'downloads.wenpai.net' ),
$url
);
// 剥离 wp_blog/wp_install 自定义 header
// 避免 WASM Service Worker fetch() 触发 CORS preflight 被 api.wenpai.net 拒绝
if ( isset( $args['headers'] ) && is_array( $args['headers'] ) ) {
unset( $args['headers']['wp_blog'], $args['headers']['wp_install'] );
}
return wp_remote_request( $new_url, $args );
},
10,
3
);
/**
* 重定向 Gravatar 头像到 Cravatar 国内源
*
* @param string $url 头像 URL
* @return string
*/
add_filter(
'get_avatar_url',
function ( $url ) {
return str_replace(
array(
'www.gravatar.com',
'0.gravatar.com',
'1.gravatar.com',
'2.gravatar.com',
'secure.gravatar.com',
'cn.gravatar.com',
),
'cn.cravatar.com',
$url
);
},
1
);