WordPress 零代碼 Head 注入 (WPCode Dynamic Injection - V1.0.6 多租戶隔離版)
無需安裝肥重外掛!將以下單一 PHP 片段貼入 WPCode,即可透過 Cloudflare Worker 依網域隔離直出包含公司、個人、碩士論文與實體的連通圖 `@graph` JSON-LD。
/**
* 【AI知識圖譜超人】Zero-Code Head 動態連通圖結構化資料注入代碼 (V1.0.6 多租戶隔離版)
* 請在 WordPress 後台 WPCode 中新增【PHP 代碼片段】並選擇【在前端整站執行 (Header)】
*/
add_action('wp_head', function () {
if (!is_singular('post')) {
return;
}
$post_id = get_the_ID();
$cache_key = 'semantic_kg_schema_' . $post_id;
$schema_json = get_transient($cache_key);
if ($schema_json === false) {
// 向 Cloudflare Worker 端點請求雙星連通圖 @graph JSON-LD,帶入 X-Tenant-Domain 絕對隔離
$cf_worker_url = "https://ai-kg-superman.iamot6.workers.dev/api/public/schema?post_id={$post_id}";
$response = wp_remote_get($cf_worker_url, [
'timeout' => 3,
'headers' => [
'Accept' => 'application/json',
'X-Tenant-Domain' => home_url()
]
]);
if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
$data = json_decode(wp_remote_retrieve_body($response), true);
if (!empty($data) && isset($data['schema'])) {
$schema_json = is_string($data['schema']) ? $data['schema'] : json_encode($data['schema'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
// 快取 7 天,達成 WordPress 主機零 MySQL 運算負載
set_transient($cache_key, $schema_json, 7 * DAY_IN_SECONDS);
}
}
}
if (!empty($schema_json)) {
echo "\n\n";
echo '\n";
}
}, 1);