萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

WordPress 文章任意位置插入百度聯盟廣告:Shortcode 與 JS 動態載入方案

方案一:WordPress Shortcode 短代碼(推薦)

在主題 functions.php 註冊短代碼,編輯文章時輸入 [bdad] 或 [bdad size="300"] 即可在任意位置顯示廣告。

// functions.php
function bdad_shortcode($atts) {
  $atts = shortcode_atts(['size' => '580'], $atts);
  $isSingle = is_single();

  if (!$isSingle) return '';

  if ($atts['size'] === '300') {
    return '
'; } else { return '
'; } } add_shortcode('bdad', 'bdad_shortcode');

方案二:JS 通用動態載入函式(非 WP 環境通用)

function dw(html) { document.write(html); }

function loadBaiduAd(cproId, type) {
  // type: 'c' = 異步載入 c.js,'f' = 同步載入 f.js
  var scriptUrl = type === 'c'
    ? 'https://cpro.baidustatic.com/cpro/ui/c.js'
    : 'https://cpro.baidustatic.com/cpro/ui/f.js';
  dw('');
  dw('');
}

// 頁面任意位置呼叫
loadBaiduAd('u1674017', 'c'); // 300x250
loadBaiduAd('u1657518', 'c'); // 580x90

進階:非同步載入避免阻塞渲染

function loadBaiduAdAsync(cproId, containerId) {
  var container = document.getElementById(containerId);
  if (!container) return;

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://cpro.baidustatic.com/cpro/ui/c.js';
  script.async = true;

  // 必須先定義 cpro_id 全域變數
  window.cpro_id = cproId;

  container.appendChild(script);
}

// HTML 預留容器
// 
//

注意事項與最佳實踐

  • HTTPS:務必使用 https://cpro.baidustatic.com 避免混合內容警告。
  • 廣告位 ID:cpro_id 需在百度聯盟後台建立對應廣告位獲取。
  • document.write 缺陷:頁面載入後呼叫會清空文檔。現代專案請改用 createElement + appendChild 或 innerHTML。
  • 廣告攔截:部分用戶使用 AdBlock,建議提供優雅降級(如顯示自薦內容)。
  • 效能:單頁過多廣告 JS 會增加主執行緒負擔,建議延遲載入(IntersectionObserver)。
copyright © 萬盛學電腦網 all rights reserved