如何使用WordPress鉤子來提高技術性SEO

如何使用WordPress鉤子來提高技術性SEO

你的網站使用WordPress作為你的CMS嗎?嘗試通過使用WordPress的動作鉤子和過濾器改善你的技術性SEO。

WordPress是世界上最流行的內容管理系統(CMS),其市場份額超過60%。

一個大的支援社羣和許多可用的免費外掛使用WordPress(WP)建立一個網站變得經濟實惠,它在其市場份額如此之大的原因中起著關鍵作用。

然而,正如你所知,安裝外掛是有代價的。

它們往往可能降低你的Core Web Vitals分數;例如,它們可能在每個頁面上載入不必要的CSS或JS檔案,而這些檔案是不需要的。

要解決這個問題,你需要僱用一個程式設計師來為你做,購買一個高階外掛,或者也許走一個小的學習途徑,自己做。

你也可以走混合型路線,通過自定義編碼解決部分問題,其他部分使用外掛。

這篇文章旨在幫助你走學習之路,我們將介紹最需要的WordPress鉤子,以幫助你提高網站的技術性SEO。

什麼是WordPress鉤子?

WordPress鉤子是WP的關鍵功能,它允許開發者擴充套件CMS的功能,而不需要修改WP的核心檔案–使更新主題或外掛更容易,而不破壞自定義的修改。

它們為開發者提供了一種強大的方式來擴充套件WordPress的功能,並對他們的網站進行自定義修改。

什麼是過濾器鉤子?

鉤子的過濾功能是用來在函式返回之前修改它的輸出的。例如,你可以使用wp_title過濾器鉤子給頁面標題加上你的部落格名稱的字尾。

什麼是動作鉤子?

動作鉤子允許程式設計師在WP核心、外掛或主題執行的特定點上執行某些動作,比如當一個帖子被髮布,或者JS和CSS檔案被載入時。

通過學習一些基本的動作鉤子或過濾器,你可以執行廣泛的任務,而不需要僱用開發人員。

我們將通過以下鉤子:

wp_enqueue_scripts

這正是你用來排除多餘的CSS或JS檔案在不需要它們的頁面上載入的動作鉤子。

例如,流行的免費Contact Form 7外掛,有超過500萬的安裝量,在所有頁面上載入CSS和JS檔案–而人們只需要它在存在聯絡表格的地方載入。

要在聯絡頁以外的頁面上排除CF7的CSS和JS檔案,你可以使用下面的程式碼片段。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function my_dequeue_script(){
//check if page slug isn't our contact page, alternatively, you can use is_page(25) with page ID, or if it is a post page is_single('my-post')
if ( !is_page('contact') ) {
wp_dequeue_script('google-recaptcha');
wp_dequeue_script('wpcf7-recaptcha');
wp_dequeue_script('contact-form-7');
wp_dequeue_style('contact-form-7');
}
}
add_action('wp_enqueue_scripts', 'my_dequeue_script', 99 );
function my_dequeue_script(){ //check if page slug isn't our contact page, alternatively, you can use is_page(25) with page ID, or if it is a post page is_single('my-post') if ( !is_page('contact') ) { wp_dequeue_script('google-recaptcha'); wp_dequeue_script('wpcf7-recaptcha'); wp_dequeue_script('contact-form-7'); wp_dequeue_style('contact-form-7'); } } add_action('wp_enqueue_scripts', 'my_dequeue_script', 99 );
function my_dequeue_script(){
//check if page slug isn't our contact page, alternatively, you can use is_page(25) with page ID, or if it is a post page is_single('my-post') 
  if ( !is_page('contact') ) {
     wp_dequeue_script('google-recaptcha');
     wp_dequeue_script('wpcf7-recaptcha');
     wp_dequeue_script('contact-form-7');
     wp_dequeue_style('contact-form-7');
  }
}
add_action('wp_enqueue_scripts', 'my_dequeue_script', 99 );

有幾個關鍵點;動作鉤子的優先順序被設定為99,以確保我們的修改在佇列中最後執行。

如果你把它設定為,比如說,10,它將不會工作,因為CF7的enqueue函式使用的是優先順序20。因此,為了確保你的修改最後執行併產生效果,請設定一個足夠大的優先順序。

另外,在程式碼中,我們使用了 “contact-form-7 “作為函式引數識別符號;你可能想知道我是如何發現的。

這是相當簡單和直觀的。只要使用瀏覽器的檢查元素工具,檢查連結或指令碼標籤的id屬性即可。

Chrome開發者工具檢查元素

Chrome開發者工具檢查元素

你可以使用檢查元素檢查你的網站原始碼,並開始對任何不需要的JS或CSS檔案進行去排隊。

這個動作鉤子是用來在網頁的<head>部分新增任何資源JS、CSS檔案或元標籤。

使用這個鉤子,你可以在頭部部分載入預裝的摺頁以上的資源,這可以提高你的LCP分數。

例如,字型預載,這是谷歌的建議之一,或者文章頁面的標誌和特色圖片,總是在摺疊上方載入–你需要預載它們來提高LCP

為此,請使用下面的程式碼片段。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function my_preload() {
?>
<!-- Google Fonts -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,200..900;1,200..900&family=Lora:ital,wght@0,400..700;1,400..700&display=swap"/>
<link rel="preload" as="image" href="https://www.yoursite.com/path-to-logo/image.jpg"/>
<?php if( has_post_thumbnail() ): // check if article has featured image?>
<!-- Featured Image -->
<?php // $featured_image = str_ireplace(array( '.png', '.jpg', '.jpeg'), '.webp', $featured_image ); // enable this if you have webp images. ?>
<?php $featured_image = get_the_post_thumbnail_url( get_the_ID(), 'full' ); ?>
<link rel="preload" as="image" href="<?php echo $featured_image;?>"/>
<?php endif;
}
add_action('wp_head', 'my_preload', 3 );
function my_preload() { ?> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,200..900;1,200..900&family=Lora:ital,wght@0,400..700;1,400..700&display=swap"/> <link rel="preload" as="image" href="https://www.yoursite.com/path-to-logo/image.jpg"/> <?php if( has_post_thumbnail() ): // check if article has featured image?> <!-- Featured Image --> <?php // $featured_image = str_ireplace(array( '.png', '.jpg', '.jpeg'), '.webp', $featured_image ); // enable this if you have webp images. ?> <?php $featured_image = get_the_post_thumbnail_url( get_the_ID(), 'full' ); ?> <link rel="preload" as="image" href="<?php echo $featured_image;?>"/> <?php endif; } add_action('wp_head', 'my_preload', 3 );
function my_preload() {
?>
   <!-- Google Fonts -->
   <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
   <link rel="preload" as="style" href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,200..900;1,200..900&family=Lora:ital,wght@0,400..700;1,400..700&display=swap"/>
   <link rel="preload" as="image" href="https://www.yoursite.com/path-to-logo/image.jpg"/>
   <?php if( has_post_thumbnail() ): // check if article has featured image?>
   <!-- Featured Image -->
   <?php // $featured_image = str_ireplace(array( '.png', '.jpg', '.jpeg'), '.webp', $featured_image ); // enable this if you have webp images. ?>
   <?php $featured_image = get_the_post_thumbnail_url( get_the_ID(), 'full' ); ?>
   <link rel="preload" as="image" href="<?php echo $featured_image;?>"/>
   <?php endif;
}
add_action('wp_head', 'my_preload', 3 );

前兩行是預裝谷歌字型,然後我們預裝標識並檢查文章是否有特色圖片,然後預裝特色圖片。

另外,你的主題或網站可能啟用了webp圖片,在這種情況下,你應該預載webp版本的圖片。

script_loader_tag

你聽說過很多關於渲染阻塞的資源,這可以通過延遲或非同步載入JavaScript標籤來解決。這對改進FCP和LCP至關重要。

這個過濾器動作是用來過濾指令碼標籤的HTML輸出的,而你正是需要這個過濾器來非同步或延遲載入你的主題或外掛的JS/CSS檔案。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function my_defer_async_load( $tag, $handle ) {
// async loading scripts handles go here as an array
$async_handles = array('wpcf7-recaptcha', 'another-plugin-script');
// defer loading scripts handles go here as an array
$defer_handles = array('contact-form-7', 'any-theme-script');
if( in_array( $handle, $async_handles) ){
return str_replace( ' src', ' async src', $tag );
}
if( in_array( $handle, $defer_handles ) ){
return str_replace( ' src', ' defer="defer" src', $tag );
}
return $tag;
}
add_filter('script_loader_tag', 'my_defer_async_load', 10, 2);
function my_defer_async_load( $tag, $handle ) { // async loading scripts handles go here as an array $async_handles = array('wpcf7-recaptcha', 'another-plugin-script'); // defer loading scripts handles go here as an array $defer_handles = array('contact-form-7', 'any-theme-script'); if( in_array( $handle, $async_handles) ){ return str_replace( ' src', ' async src', $tag ); } if( in_array( $handle, $defer_handles ) ){ return str_replace( ' src', ' defer="defer" src', $tag ); } return $tag; } add_filter('script_loader_tag', 'my_defer_async_load', 10, 2);
function my_defer_async_load( $tag, $handle ) {
   // async loading scripts handles go here as an array
   $async_handles = array('wpcf7-recaptcha', 'another-plugin-script');
   // defer loading scripts handles go here as an array
   $defer_handles = array('contact-form-7', 'any-theme-script');
   if( in_array( $handle, $async_handles) ){
     return str_replace( ' src', ' async src', $tag );
   }
   if( in_array( $handle, $defer_handles ) ){
     return str_replace( ' src', ' defer="defer" src', $tag );
   }
return $tag;
}
add_filter('script_loader_tag', 'my_defer_async_load', 10, 2);

這個過濾器接受兩個引數: HTML標籤和指令碼控制代碼,這是我在上面通過檢查元素檢查時提到的。

你可以使用控制代碼來決定是非同步載入還是延遲載入哪個指令碼。

在你延遲或非同步載入後,總是通過瀏覽器控制檯檢查是否有任何JS錯誤。如果你看到JS錯誤,你可能需要一個開發人員來幫助你,因為修復它們可能並不簡單。

template_redirect

這個動作鉤子在決定載入哪個模板之前被呼叫。你可以用它來改變響應的HTTP狀態程式碼。

例如,你可能有指向你的內部搜尋查詢頁面的垃圾反向連結,其中包含奇怪的字元和/或常見模式。

有垃圾反向連結指向我們的內部搜尋頁面,這些頁面是韓文的–而且我們從伺服器日誌中瞭解到,Googlebot正在密集地抓取這些頁面。

韓語文字外部連結

韓語文字外部連結

WordPress預設的響應程式碼是404未找到,但最好扔進410,以便告訴Google它們永遠消失了,所以它停止抓取它們。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function my_410_function(){
if( is_search() ) {
$kw = $_GET['s'];
// check if the string contains Korean characters
if (preg_match('/[\x{AC00}-\x{D7AF}]+/u', $kw)) {
status_header(410, 'Not Found');
}
}// end of is_search
}
add_action( 'template_redirect', 'my_410_function', 10 );
function my_410_function(){ if( is_search() ) { $kw = $_GET['s']; // check if the string contains Korean characters if (preg_match('/[\x{AC00}-\x{D7AF}]+/u', $kw)) { status_header(410, 'Not Found'); } }// end of is_search } add_action( 'template_redirect', 'my_410_function', 10 );
function my_410_function(){
  if( is_search() ) {
    $kw = $_GET['s'];
  // check if the string contains Korean characters
  if (preg_match('/[\x{AC00}-\x{D7AF}]+/u', $kw)) {
     status_header(410, 'Not Found');
    }
  }// end of is_search
}
add_action( 'template_redirect', 'my_410_function', 10 );

在上面的案例中,源站沒有韓國的內容,這就是為什麼我們的條件是這樣構成的。

但你可能有韓語的國際內容,條件可能會有所不同。

一般來說,對於非程式設計師來說,ChatGPT是一個使用正規表示式生成條件的好工具,你可以用它來建立一個基於GSC的垃圾連結模式的if/else條件。

wp_headers

這個動作鉤子是用來修改WordPress的HTTP標頭的。

你可以使用這個鉤子在你的網站響應的HTTP標頭資訊中新增安全標頭資訊。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function my_headers(){
$headers['content-security-policy'] = 'upgrade-insecure-requests';
$headers['strict-transport-security'] = 'max-age=31536000; preload';
$headers['X-Content-Type-Options'] = 'nosniff';
$headers['X-XSS-Protection'] = '1; mode=block';
$headers['x-frame-options'] = 'SAMEORIGIN';
$headers['Referrer-Policy'] = 'strict-origin-when-cross-origin';
$headers['Link'] = '<https://www.yoursite.com/wp-content/uploads/themes/yourtheme/images/logo.jpg>; rel=preload; as=image';
$headers['Link'] = '<https://fonts.gstatic.com>; rel=preconnect; crossorigin';
$headers['Link'] = '</wp-content/uploads/themes/yourtheme/images/logo.webp>; rel=preload; as=image';
return $headers;
}
add_filter( 'wp_headers', 'my_headers', 100 );
function my_headers(){ $headers['content-security-policy'] = 'upgrade-insecure-requests'; $headers['strict-transport-security'] = 'max-age=31536000; preload'; $headers['X-Content-Type-Options'] = 'nosniff'; $headers['X-XSS-Protection'] = '1; mode=block'; $headers['x-frame-options'] = 'SAMEORIGIN'; $headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'; $headers['Link'] = '<https://www.yoursite.com/wp-content/uploads/themes/yourtheme/images/logo.jpg>; rel=preload; as=image'; $headers['Link'] = '<https://fonts.gstatic.com>; rel=preconnect; crossorigin'; $headers['Link'] = '</wp-content/uploads/themes/yourtheme/images/logo.webp>; rel=preload; as=image'; return $headers; } add_filter( 'wp_headers', 'my_headers', 100 );
function my_headers(){
      $headers['content-security-policy'] = 'upgrade-insecure-requests';
      $headers['strict-transport-security'] = 'max-age=31536000; preload';
      $headers['X-Content-Type-Options'] = 'nosniff';
      $headers['X-XSS-Protection'] = '1; mode=block';
      $headers['x-frame-options'] = 'SAMEORIGIN';
      $headers['Referrer-Policy'] = 'strict-origin-when-cross-origin';
      $headers['Link'] = '<https://www.yoursite.com/wp-content/uploads/themes/yourtheme/images/logo.jpg>; rel=preload; as=image';
     $headers['Link'] = '<https://fonts.gstatic.com>; rel=preconnect; crossorigin'; 
$headers['Link'] = '</wp-content/uploads/themes/yourtheme/images/logo.webp>; rel=preload; as=image';
      return $headers;
 }
add_filter( 'wp_headers', 'my_headers', 100 );

除了安全標題之外,你還可以新增 “Link”標籤(想加多少就加多少),以預先連線或預先載入任何資源。

基本上,這是一種預載入的替代方法,上面已經介紹了。

你也可以根據你的需要在你的HTTP標標頭檔案中新增 “X-Robots-Tag”(想加多少就加多少)。

小結

外掛往往是為了解決各種各樣的任務,而且往往可能不是為了滿足你的特定需求而專門設計的。

你可以輕鬆地修改WordPress的核心,這是它最美麗的方面之一–而且你可以用幾行程式碼來改變它。

我們討論了你可以用來改善技術性SEO的動作鉤子,但是WordPress有大量的動作鉤子,你可以探索和使用它們來做基本上所有你想做的事情,而只需使用最少的外掛。

評論留言