問題描述

我正在處理一個 SSL 問題,我想從所有腳本和樣式中刪除域,通過 wp_enqueue_scripts 輸出。這將導致所有腳本和樣式都顯示與域根的相對路徑。

我想象有一個鈎子,我可以用來詆譭這個,但是,我不知道哪一個,也不知道該怎麼做。

最佳解決思路

與 Wyck 的答案相似,但使用 str_replace 而不是正則表達式。

script_loader_srcstyle_loader_src 是你想要的鈎子。

<?php
add_filter( 'script_loader_src', 'wpse47206_src' );
add_filter( 'style_loader_src', 'wpse47206_src' );
function wpse47206_src( $url )
{
    if( is_admin() ) return $url;
    return str_replace( site_url(), '', $url );
}

您也可以使用雙斜線//(「network path reference」) 啓動腳本/樣式 URL 。哪個可能更安全 (?):仍然有完整的路徑,但使用當前頁面的方案/協議。

<?php
add_filter( 'script_loader_src', 'wpse47206_src' );
add_filter( 'style_loader_src', 'wpse47206_src' );
function wpse47206_src( $url )
{
    if( is_admin() ) return $url;
    // why pass by reference on count? last arg
    return str_replace( array( 'http:', 'https:' ), '', $url, $c=1 );
}

次佳解決思路

是的,我認為它的可能。見過濾鈎 script_loader_src; 有字符串,您可以根據您的要求過濾。

add_filter( 'script_loader_src', 'fb_filter_script_loader', 1 );
function fb_filter_script_loader( $src ) {

    // remove string-part "?ver="
    $src = explode( '?ver=', $src );

    return $src[0];
}
  • 寫在頭上,沒有測試

樣式表也是如此,通過帶有過濾器 style_loader_srcwp_enqueue_style 進行加載。

第三種解決思路

另一種方式,我認為從根主題,可能有點貧民窟,但有一些聰明的處理,何時使用相對的 urls(只測試在開發網站) 。它的好處是可以用作 WordPress 使用的許多其他內置 URL 的過濾器。此示例僅顯示樣式和腳本入隊過濾器。

function roots_root_relative_url($input) {
  $output = preg_replace_callback(
    '!(https?://[^/|"]+)([^"]+)?!',
    create_function(
      '$matches',
      // if full URL is site_url, return a slash for relative root
      'if (isset($matches[0]) && $matches[0] === site_url()) { return "/";' .
      // if domain is equal to site_url, then make URL relative
      '} elseif (isset($matches[0]) && strpos($matches[0], site_url()) !== false) { return $matches[2];' .
      // if domain is not equal to site_url, do not make external link relative
      '} else { return $matches[0]; };'
    ),
    $input
  );

  /**
   * Fixes an issue when the following is the case:
   * site_url() = http://yoursite.com/inc
   * home_url() = http://yoursite.com
   * WP_CONTENT_DIR = http://yoursite.com/content
   * http://codex.wordpress.org/Editing_wp-config.php#Moving_wp-content
   */
  $str = "/" . end(explode("/", content_url()));
  if (strpos($output, $str) !== false) {
    $arrResults = explode( $str, $output );
    $output = $str . $arrResults[1];
  }

  return $output;

if (!is_admin()) {
  add_filter('script_loader_src', 'roots_root_relative_url');
  add_filter('style_loader_src', 'roots_root_relative_url');
 }

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。