WordPress掛鉤訓練營:如何使用動作,過濾器和自定義掛鉤

WordPress掛鉤是WordPress開發人員的工具庫中最重要的工具之一。它們是WordPress插件和主題開發的基礎。您可以使用WordPress的許多內置掛鉤,通過您的自定義代碼「掛鉤」到WordPress核心中,然後執行或修改某些內容。

#js-mykinsta-video {
背景圖片:url(https://kinsta.com/wp-content/themes/kinsta/images/mykinsta-dashboard-v8@2x.jpg);
}

免費試用

WordPress掛鉤有兩種類型:操作和過濾器。鉤子如此普遍,以至於WordPress Core本身都廣泛使用它們。 WordPress還提供了一種定義自己的自定義鉤子的方法,以便其他開發人員可以鉤入您的代碼。

學習動作,過濾器和自定義鉤子如何工作對於掌握WordPress開發至關重要。

本文的前半部分介紹了WordPress鉤子的基礎知識,並說明了它們如何與多個示例一起使用。在下半年,您將學習如何使用鉤子自定義WordPress,創建自己的自定義鉤子以及如何使用它們來構建自己的可擴展插件。

聽起來很令人興奮?讓我們潛入吧!

什麼是WordPress掛鉤?

WordPress頁面由大量功能和資料庫查詢組成。 WordPress核心,插件和主題一起工作以輸出頁面元素,例如文本,圖像,腳本和樣式。完全組裝後,瀏覽器然後將它們放在一起並呈現頁面。

WordPress掛鉤可讓您在某些時候「掛鉤」此構建過程並運行自定義代碼。掛鉤的主要功能是允許您修改WordPress或向其中添加功能,而無需接觸核心文件。

WordPress掛鉤如何工作的圖形表示

掛鉤將幫助您使用自己的代碼擴展WordPress

WordPress插件API支持WordPress掛鉤的功能。您可以通過在WordPress運行時期間的特定實例調用稱為鉤子函數的某些WordPress函數來使用鉤子。

使用掛鉤函數,您可以將自定義代碼捆綁在回調函數中,並將其註冊到任何掛鉤中。一旦註冊,該回調函數將在鉤子所在的任何位置運行,從而允許您擴充或替換默認的WordPress功能。

掛鉤在代碼執行過程中的位置是一個重要因素。您將在接下來的部分中詳細了解其重要性。

通過本WordPress鉤子指南迷上#webdev。 ⚡️

點擊鳴叫

兩種類型的WordPress掛鉤:操作和過濾器

WordPress包含兩種類型的掛鉤,分別稱為Actions和Filters。通過操作,您可以在WordPress運行時的某些預定義點進行操作,而使用過濾器,則可以修改WordPress處理的任何數據並返回。

動作在WordPress代碼中定義為:

do_action(’action_name’, [optional_arguments] );

action_name字元串是操作的名稱。您可以指定 [optional_arguments] 變數以將其他參數傳遞給回調函數。如果未指定此欄位,則其默認值為空。

示例:每次WordPress處理站點標頭時,都可以將do_action(’wp_head’)操作掛鉤以運行自定義代碼。此操作沒有其他任何參數。

過濾器在WordPress代碼中定義為:

apply_filters(’filter_name’,’value_to_be_filtered’, [optional_arguments] );

filter_name字元串是過濾器的名稱,value_to_be_filtered變數是需要過濾並返回的值,並且 [optional_arguments] 變數可以傳遞其他參數,就像操作一樣。

示例:apply_filters(’admin_footer_text’,string $ text)過濾器可以被掛鉤,以修改顯示在admin頁腳中的文本。從WordPress 5.4開始,其默認值將顯示句子感謝您使用WordPress創建。在管理區域頁腳中。

稍後,您將通過WordPress Core中的許多示例來學習如何進行操作和過濾。

上鉤後,您可以指導您的代碼執行或自定義網站上的某些內容。例如,您可以在發布帖子後使用彎鉤發送自動電子郵件,或載入自定義樣式表以更改網站的外觀。

想像將動作和過濾器掛鉤就像蓋房子一樣

WordPress掛鉤可幫助您與網站互動或修改網站

理解鉤子的最簡單方法是將您的WordPress網站想像為蓋房子。

鉤子類似於使用起重機來回移動建築物。轉移的項目是包括您的自定義代碼的回調功能。這些項目(或功能)可以幫助您建造或修改房屋。

使用內部示例在WordPress中掛接到'wp_head'操作的示例

在WordPress中加入「 wp_head」操作的示例

回調函數可以是常規PHP函數,默認WordPress函數或您定義的自定義函數。

我們只能在連接到特定掛鉤的特定托架上攜帶某些物品。因此,動作只能與動作功能掛鉤。同樣,過濾器只能與過濾器功能掛鉤。

儘管更換起重機上的吊鉤和托架很繁瑣,但WordPress通過包含2200多種默認吊鉤類型,使超級簡單。

該圖顯示了WordPress鉤子隨時間的擴散

WordPress 5.1具有2200多個本機掛鉤(來源:亞當·布朗)

您可以找到散布在WordPress核心上的鉤子,使您可以準確地鉤入要鉤入的位置並運行自定義代碼。

WordPress掛鉤可讓您「融入」頁面構建過程…並讓您對自己創建的內容擁有更多控制權。

點擊鳴叫

鉤子vs動作vs過濾器

根據WordPress插件手冊:

「掛鉤是一種代碼用於交互/修改另一段代碼的方式……掛鉤有兩種類型:動作和過濾器。」

在使用「掛鉤」,「操作」和「過濾器」等術語時存在廣泛的不一致之處。一些教程和指南將它們與與其關聯的功能混合在一起。存在這種混亂的主要原因是由於掛鉤的工作方式複雜。

即使您仔細查看WordPress核心,也會發現添加操作和過濾器之間並沒有太大區別。這是wp-includes / plugin.php文件中add_action()函數的源代碼:

函數add_action($ tag,$ function_to_add,$ priority = 10,$ accepted_args = 1){
    返回add_filter($ tag,$ function_to_add,$ priority,$ accepted_args);
}

add_action()函數僅調用add_filter()函數並返回其值。為什麼?因為除了一個區別外,它們基本上都以相同的方式工作。

apply_filters()函數返回的值可以更改現有數據類型,而do_action()函數則不返回任何值(PHP中為NULL值)。

如果您仍然感到困惑,請不要擔心!讀完本文的上半部分後,一切都會清楚了。我們將使用官方WordPress Codex術語,因為它是清晰,精確和通用的。

現在,使您熟悉以下所示的掛鉤常式。

表示WordPress中典型的``掛鉤常式''的信息圖

掛鉤常式:掛鉤,掛鉤函數和回調函數

讓我們分解一下動作和掛鉤之間的區別。

WordPress掛鉤
動作 篩選器
在WordPress Core執行期間,動作用於在特定位置運行自定義功能。 過濾器用於修改或自定義其他功能使用的數據。
動作是由WordPress代碼中的函數do_action(「 action_name」)定義/創建的。 過濾器是由WordPress代碼中的apply_filters(“filter_name”,“value_to_be_filtered”)函數定義/創建的。
動作也稱為動作掛鉤。 過濾器也稱為過濾器掛鉤。
只能將動作與動作功能掛鉤。例如。 add_action(),remove_action()。 篩選器只能與「篩選器」功能掛鉤。例如。 add_filter(),remove_filter()。
動作函數無需向其回調函數傳遞任何參數。 過濾器函數需要至少將一個參數傳遞給其回調函數。
動作功能可以執行任何類型的任務,包括更改WordPress工作方式的行為。 過濾器功能僅用於修改過濾器傳遞給它們的數據。
動作函數應不返回任何內容。但是,它們可以回顯輸出或與資料庫交互。 過濾器函數必須將其更改作為輸出返回。即使過濾器功能沒有任何變化,它也必須返回未修改的輸入。
只要代碼有效,動作幾乎可以執行任何操作。 過濾器應以隔離的方式工作,因此不會有任何意外的副作用。
簡介:一個操作會中斷常規代碼執行過程,以對其接收到的信息執行某些操作,但不返回任何內容,然後退出。 摘要:過濾器修改接收到的信息,將其返回給調用鉤子函數,其他函數可以使用其返回的值。

有時,您可以使用操作或過濾器來實現相同的目標。例如,如果您要修改帖子中的文本,則可以在publish_post操作中註冊一個回調函數,並在將帖子內容保存到資料庫時對其進行更改。

//定義回調函數以更改文本
函數change_text_callback(){
    //在此處添加代碼以更改文本
}

//使用add_action()函數掛接到’publish_post’操作
add_action(’publish_post’,’change_text_callback’);

或者,您也可以使用-content過濾器註冊另一個回調函數,以在帖子內容在瀏覽器中顯示之前對其進行修改。

//定義回調函數以修改文本
函數change_text_another_callback($ content){
    //添加代碼以在此處更改文本,然後返回
    返回$ filtered_content;
}

//使用add_filter()函數連接到「 the_content」過濾器
add_filter(’the_content’,’change_text_another_callback’);

兩種不同的方法具有相同的結果。知道何時使用一個人是成為一個好的WordPress開發人員的關鍵。

WordPress掛鉤如何工作?

內部示例很簡單,足以理解鉤子的基本功能,但沒有抓住鉤子工作原理的複雜性。最重要的是,掛鉤位置和特異性的概念。

一個更好的例子是想像將WordPress網頁處理為組裝汽車。不同於製造汽車要花費時間,組裝網頁幾乎是瞬間的。

該圖顯示了組裝網頁類似於組裝車輛

組裝網頁就像組裝汽車

就像汽車如何在現代裝配線中進行逐部分組裝一樣,WordPress網頁由伺服器和客戶端逐個元素地組裝。

WordPress核心就像汽車引擎,底盤和其他必需品一樣,為網站的「核心」功能提供了動力。

您可以擁有僅具有WordPress Core的功能性網站,但是這樣做的樂趣何在?您需要向網站添加令人興奮的功能。這就是WordPress插件和主題介入的地方,它們都廣泛使用鉤子。

在上面的示例中,每個編號的工作站都像WordPress核心內的一個鉤子。站有兩種,例如動作和過濾器。每個工作站都包含一種特定類型的插槽,僅接受某些工具,類似於動作功能和過濾器功能。

為了模塊化和高效率,所有站點都按一定間隔放置。

根據特定位置的要求,我們可以為該特定工位安裝(或鉤住)最合適的工具。這些工具就像用於與WordPress進行交互或修改WordPress的回調函數一樣。

一些工具可以極大地改變汽車的工作方式,就像註冊為操作的回調一樣。其他工具僅用於自定義汽車的外觀,例如註冊到過濾器的回調。

在正確的位置使用正確的工具對於製造一流的汽車至關重要。同樣,鉤子可以幫助我們根據我們的獨特需求自定義WordPress。

如果您以此類推,則插件就像添加了有用的汽車功能,例如安全氣囊,娛樂控制台,遠程無鑰匙系統等(這些都是為了增強WooCommerce的功能)。主題類似於自定義汽車的視覺部分,例如總體設計,油漆作業,輪輞等(此處是自定義WordPress主題的方法)。

在哪裡註冊鉤子及其功能?

有兩種推薦的方法可以在WordPress中添加鉤子:

  • 插件:製作自己的插件,並在其中添加所有自定義代碼。
  • 子主題:在子主題的functions.php文件中註冊鉤子和回調函數。

對於本教程,我們首先創建一個插件。為此,請在/ wp-content / plugins /目錄中創建一個新文件夾。

我的插件名稱是salhooks,但您可以根據需要命名。根據WordPress準則,您需要在插件目錄中創建一個具有相同名稱(salhooks.php)的PHP文件。

將以下標頭欄位添加到您的插件文件中,以在WordPress中進行註冊。您可以在WordPress Codex中了解有關插件標頭要求的更多信息。

<?php / * 插件名稱:Salhooks 版本:1.0 說明:通過多個示例演示WordPress掛鉤(操作和過濾器)。 作者:Salman Ravoof 作者URI:https://www.salmanravoof.com/ 許可證:GPLv2或更高版本 許可URI:https://www.gnu.org/licenses/gpl-2.0.html 文本域:salhooks * / // ================================================ = //安全性:如果直接調用此文件,則中止 // ================================================ = 如果(!defined('ABSPATH')){     死; }

保存此文件,然後在WordPress儀錶板中激活插件。我將在本地WordPress安裝中使用此插件來演示鉤子如何工作。

另外,您還可以直接編輯WordPress Core文件以註冊鉤子。但是,不建議您這樣做,因為每次更新WordPress時,所有自定義代碼都會被覆蓋。出於同樣的原因,您不應該在父主題中添加鉤子。

使用WordPress掛鉤

WordPress掛鉤本身不執行任何操作。它只是位於代碼中,等待一些掛鉤函數將其激活。要使用鉤子,您需要調用至少兩個其他函數。

首先,您需要向鉤子註冊一個鉤子函數,並在其中引用一個回調函數。然後,您需要定義鉤子函數中前面提到的回調函數。每次鉤子觸發時,WordPress都會運行此回調函數。

定義這些功能的順序並不重要,但最好將它們放在一起。

動作和過濾器具有獨特的掛鉤函數。從現在開始,我們將它們稱為「動作功能」和「過濾器功能」。如您所見,它們具有自己的語法和參數要求。

掛鉤動作

動作提供了一種在WordPress Core,插件或主題執行的特定時間運行自定義代碼的方法。

add_action()動作函數

您可以按照以下步驟向操作註冊回調函數:

  1. 使用內部的自定義代碼定義回調函數。當在WordPress的代碼執行過程中觸發了向其註冊的任何操作時,此回調函數將運行。
  2. 使用add_action()函數將回調函數與所需的動作掛鉤。根據WordPress Codex,add_action()函數需要傳遞至少兩個參數:
      • 要掛接到的動作的名稱。
      • 觸發操作時將運行的回調函數的名稱。
  3. add_action()函數還接受兩個可選參數來設置優先順序和參數數量。我們稍後將討論它們。

最好將回調函數的參數命名為儘可能接近hook函數傳遞的參數。

讓我們看一個使用add_action()函數的示例。

//定義回調函數,參數是可選的
函數example_callback($ arg1,$ arg2){
//使您的代碼對參數執行某些操作
}

//將回調函數掛鉤到’example_action’
add_action(’example_action’,’example_callback’, [priority], [no_of_args] );

//’priority’和’arguments’是可選參數
掛鉤動作的例子

WordPress包含一個名為init的內置操作,該操作在WordPress完成載入並驗證用戶身份之後但在發送任何標頭之前觸發。許多插件使用此鉤子作為實例化其代碼的起點,因為在WordPress運行此操作時,幾乎所有主要WordPress功能都已完成載入。

WordPress具有類似的名為admin_init的操作。在初始化管理屏幕時觸發,而僅在WordPress完成載入後才觸發init操作。

讓我們運行一個自定義代碼,以在執行init操作期間回顯一條簡單的消息。方法如下:

函數custom_callback_function(){
//在此處添加您的自定義代碼以執行某些操作
回顯「我將在WordPress初始化上被解僱」;
}
add_action(’init’,’custom_callback_function’);

您可以在本地WordPress安裝的左上角看到正在回顯的消息。

使用WordPress中的init動作鉤子回顯消息

並不是那麼漂亮,但這是一個很好的開始!

查找WordPress支持的操作

WordPress每次執行某項操作時都會包含操作,例如用戶登錄或發布新帖子。您可以在「插件API /操作參考」頁面中找到WordPress運行的所有操作的完整列表。

WordPress Codex中「插件API」部分的「操作」參考頁

幾乎所有用途都有一個動作

食品法典將其中列出的所有動作分為不同的類別,並按照WordPress執行順序從頭到尾進行了排列。

在大多數情況下,這些操作中的許多操作都無濟於事,因為沒有任何關聯。但是,如果您需要它們,它們就會在那裡供您使用。

對所有動作感到有點不知所措?很自然隨著您獲得更多經驗並遍歷WordPress Core源代碼,可以更輕鬆地找到適合您需要的鉤子。只需搜索「 do_action」一詞,您就會發現很多可以掛接到的動作。

add_action()的附加參數

add_action()函數可以接受另外兩個參數:一個用於設置優先順序,另一個用於設置參數數量。儘管它們是可選的,但如果使用正確,它們會非常有用。

優先

add_action()函數支持的第一個附加參數設置優先順序。此參數只能是一個正整數。優先順序數字越低,該功能將越早運行。如果未指定,則默認值為10。

為了了解其工作原理,讓我們為init操作註冊三個回調函數,但每個函數具有不同的優先順序。

//優先順序設置為9,低於10,因此排名更高
add_action(’init’,’i_am_high_priority’,9);

//如果未設置優先順序,則將使用默認值10
add_action(’init’,’i_am_default_priority’);

//優先順序設置為11,高於11,因此排名較低
add_action(’init’,’i_am_low_priority’,11);

在上面的示例中,優先順序最低的回調函數將首先運行,而優先順序最高的回調函數將最後運行。如果它們的優先順序相同,那麼它們將按照您註冊它們的順序運行。

當單個鉤子可以向其註冊多個回調函數時,優先順序起著重要作用。為避免意外結果,您可以為每個回調函數設置優先順序,以便它們按您希望的順序啟動。

參數個數

默認情況下,通過add_action()函數註冊的任何回調函數將僅接收一個參數。但是,有時您可能需要將額外的數據傳遞給回調函數。

因此,add_action()函數接受用於設置參數數量的可選參數。

展示這一點的一個很好的例子是comment_post動作。 WordPress向資料庫添加註釋後,此操作將立即運行。如果您未設置arguments of parameter參數,它將僅將一個值傳遞給回調函數,在本例中為comment_ID。

//用’priority’和’arguments’參數註冊鉤子
add_action(’comment_post’,’show_message_function’,10,3);

//定義回調函數
函數show_message_function($ comment_ID,$ comment_approved,$ commentdata){
//檢查是否使用第二個參數批准了注釋
if(1 === $ comment_approved){
//僅在批准注釋後才運行代碼
}
}

如果如上例中那樣將arguments參數的數量設置為3,則動作函數將傳遞三個值:comment_ID,comment_approved和commentdata。

WordPress將已批准的評論的comment_approved值設置為1,如果未批准,則將其設置為0,如果評論標記為垃圾郵件,則將其設置為「 spam」。

commentdata變數是一個數組,其中包含所有評論數據,例如評論作者的姓名,電子郵件地址,網站以及評論本身的內容。您可以查看WordPress Codex來查找「 commentdata」數組中包含的所有鍵值對。

您可以根據需要設置任意數量的參數,但是回調函數和add_action()函數需要指定相同數量的參數。

通過將其他參數傳遞給回調函數,您可以對代碼執行更多操作。例如,您可以檢查評論是否被批准,如果評論文本獲得批准,則會自動通過電子郵件將其發送給管理員。如果不指定其他參數,則無法執行此操作,因為您的回調函數將無法訪問comment_content數據。

如果您不想設置優先順序,而只想更改參數數量,則仍然需要設置優先順序。只需使用其默認值(即10)即可。

WordPress核心如何使用動作

WordPress Core本身使用其許多內置動作來執行各種功能。

以wp_head操作為例。當WordPress輸出網頁的標頭部分(介於兩者之間的代碼 和 )。

您可以在wp-includes / default-filters.php文件中找到與wp_head掛鉤相關的大多數WordPress Core動作功能。我遍歷了代碼,並編譯了所有調用wp_head動作的add_action()函數的列表。

add_action(’wp_head’,’rest_output_link_wp_head’,10,0);
add_action(’wp_head’,’_wp_render_title_tag’,1);
add_action(’wp_head’,’wp_enqueue_scripts’,1);
add_action(’wp_head’,’wp_resource_hints’,2);
add_action(’wp_head’,’feed_links’,2);
add_action(’wp_head’,’feed_links_extra’,3);
add_action(’wp_head’,’rsd_link’);
add_action(’wp_head’,’wlwmanifest_link’);
add_action(’wp_head’,’adjacent_posts_rel_link_wp_head’,10,0);
add_action(’wp_head’,’locale_stylesheet’);
add_action(’wp_head’,’noindex’,1);
add_action(’wp_head’,’print_emoji_detection_script’,7);
add_action(’wp_head’,’wp_print_styles’,8);
add_action(’wp_head’,’wp_print_head_scripts’,9);
add_action(’wp_head’,’wp_generator’);
add_action(’wp_head’,’rel_canonical’);
add_action(’wp_head’,’wp_shortlink_wp_head’,10,0);
add_action(’wp_head’,’wp_custom_css_cb’,101);
add_action(’wp_head’,’wp_site_icon’,99);
add_action(’wp_head’,’wp_no_robots’);

很多回調函數只需要執行一項操作即可。在此處設置優先順序對於確保最重要的掛鉤函數首先運行至關重要。

在上面的示例中,使用wp_enqueue_scripts()回調函數載入腳本(優先順序= 1)比使用wp_site_icon()回調函數載入網站圖標元標記(優先順序= 99)更為重要。

信息

上例中使用的所有回調函數都是WordPress函數。您也可以在任何代碼中使用它們。有關更多信息,請訪問WordPress Codex上的Function Reference頁面。

其他動作功能

儘管add_action()是最常用的操作函數,但還有許多其他功能同樣有用。讓我們看看它們如何工作。

  • has_action()

該動作功能檢查是否已鉤住動作。它接受兩個參數。第一個是動作的名稱。第二個參數是可選的,是回調函數的名稱。

has_action(’action_name’,’function_to_check’);

如果僅指定第一個參數,則將任何函數掛接到action_name參數時,它將返回true。

但是,如果您還指定了第二個參數,則在指定的回調函數未註冊到上述操作的情況下,它將返回false。

但是,如果它找到附加在動作掛鉤上的回調函數,它將返回在該動作掛鉤上為此函數設置的優先順序(整數)。

  • do_action()

我們之前遇到過此操作功能。 WordPress使用它來定義其所有默認操作,從而使其他功能可以與它們掛鉤。與WordPress一樣,您也可以使用do_action()函數通過指定新的操作名稱作為參數來創建新的自定義操作。

do_action(’action_name’, [argument1], [argument2] );

僅聲明此功能本身不會做任何事情。但是它將位於代碼中,等待其他操作功能將其激活。傳遞任何其他參數是可選的,但如果您希望回調函數使用它們,則這一點很重要。

  • do_action_ref_array()

除了一個不同之外,該動作函數與do_action()相同。通過它的任何參數都必須是一個數組。當您有很多要傳遞的參數或參數已在數組中時,此函數非常有用。

使用WordPress,我們的流量增長了1,187%。
我們將向您展示如何。
加入20,000多個其他人,他們每周都會收到有關WordPress內部技巧的新聞!

          現在訂閱
        
        
          
            
            成功!感謝您的訂閱

您將在一周內收到下一期的Kinsta新聞通訊。

訂閱Kinsta新聞通訊
        
  
    
      
    
      
        訂閱
    
  
  
    

我同意條款和條件以及隱私政策

  

      

//這是一個示例數組
$ arguments_array = array(’arg_1’,’foo’,true,’arg_4’);

do_action_ref_array(’example_action’,$ arguments_array);

由於PHP數組是有序映射,因此請確保傳遞的參數順序正確。

此操作功能用法的一個示例是admin_bar_menu操作。可以將其掛鉤以添加,操作或刪除各種管理欄項目。所有管理欄項目均定義為數組的元素。

  • did_action()

如果要計算觸發任何動作的次數,可以調用此動作功能。

did_action(’action_name’);

該函數返回一個整數值。

當您只想在第一次運行一個動作而不再運行一次回調函數時,did_action()函數非常方便。

函數example_callback_function(){
    if(did_action(’example_action’)=== 1){
    //檢查’example_action’掛鉤是否被觸發過一次,然後才運行,再也不會運行!
    }
}
add_action(’example_action’,’example_callback_function’);

  • remove_action()

此動作函數將刪除掛接到指定動作的回調函數。例如,您可以使用此功能刪除掛鉤到內置操作中的默認WordPress功能,並將其替換為您自己的默認功能。

remove_action(’action_name’,’function_to_be_removed’, [priority] );

調用remove_action()函數有一些先決條件:

  1. function_to_be_removed和priority參數必須與add_action()函數中最初使用的參數相同。
  2. 您不能直接調用remove_action()函數。您需要從另一個函數內部調用它。
  3. 如果回調函數是從類中註冊的,則刪除它還有其他要求。您可以查看WordPress Codex文檔以了解更多詳細信息。
  4. 在回調函數註冊之前或運行之後,您無法刪除它。

這是WooCommerce如何使用此操作功能刪除商店主頁面上默認商品縮略圖的示例。

remove_action(’woocommerce_before_shop_loop_item_title’,’woocommerce_template_loop_product_thumbnail’,10);

  • remove_all_actions()

該動作功能可刪除與動作相關的所有內容。 priority參數是可選的。

remove_all_actions(’action_name’, [priority] );

請記住,您要從中註銷回調函數的操作無法調用此函數。這將導致無限循環。您可以加入之前觸發的操作來運行此功能,而不會出現任何錯誤。

  • doing_action()

該動作功能檢查指定的動作是否正在運行。它返回一個布爾值(真或假)。

//檢查是否正在執行「 action_name」操作
如果(do_action(’action_name’)){
//在這裡執行您的代碼
}

您可以將action_name參數留空以檢查是否正在執行任何動作。每當執行任何操作時,它都會返回true。

//檢查是否正在執行任何操作並執行某些操作
如果(do_action()){
  //當執行任何操作時,此處的代碼將運行
}
動作示例1:向網站訪問者顯示維護消息

有時,最好使您的網站離線並設置「維護中」頁面。幸運的是,WordPress提供了一種簡單的方法來做到這一點。

//向所有網站訪問者顯示維護消息
add_action(’get_header’,’maintenance_message’);
函數maintenance_message(){
    如果(current_user_can(’edit_posts’))返回;
    wp_die(’

保持謹慎!

抱歉,我們暫時無法進行維護。」 );
}

讓我們分解代碼並完成每個步驟:

  • get_header是在載入網站的標題模板文件之前觸發的操作。如果要中斷主站點的載入,這是一個完美的選擇。
  • 使用帶有add_action()函數和maintenance_message()回調函數的get_header動作。
  • 定義maintenance_message()回調函數。
  • current_user_can(’edit_posts’)是一個用戶能力測試功能,用於檢查當前用戶是否已登錄並可以編輯帖子。在WordPress網站上註冊的每個用戶(具有訂閱者角色的用戶除外)都可以編輯帖子。還有其他健壯的方法可以執行此檢查,但是在這裡我們將堅持使用這種簡單的方法。
  • 使用默認的wp_die()函數優雅地終止WordPress執行並顯示帶有錯誤消息的HTML頁面。您可以在錯誤消息參數中使用HTML語法來設置其格式。

將代碼保存在自定義插件中後,我以私人瀏覽模式載入了本地WordPress安裝。維護不足頁面成功!

向站點的訪問者顯示維護不足頁面

向網站訪問者顯示錯誤消息

如果我通過用戶功能測試後登錄,則該網站將成功載入。現在,您可以繼續修復您的網站,同時它向普通訪問者顯示此頁面。

操作示例2:向非管理員用戶隱藏儀錶板菜單項

如果您正在運行多作者博客或為客戶管理網站,則可能需要為非管理員用戶從WordPress儀錶板中隱藏某些管理員菜單。您可以通過加入admin_menu操作來實現。

//刪除非管理員用戶的特定儀錶板菜單
add_action(’admin_menu’,’hide_admin_menus’);
函數hide_admin_menus(){
    如果(current_user_can(’create_users’))返回;
    如果(wp_get_current_user()-> display_name ==「 Salman」)返回;
    remove_menu_page( ‘plugins.php’ );
    remove_menu_page( ‘themes.php’ );
    remove_menu_page( ‘tools.php’ );
    remove_menu_page( ‘users.php’ );
    remove_menu_page( ‘edit.php?post_type=page’ );
    remove_menu_page( ‘options-general.php’ );
}

Here』s a step-by-step walkthrough of the code snippet above:

  • admin_menu is an action that』s triggered before the admin menu loads in the WordPress dashboard area.
  • Hook into the admin_menu action using the add_action() function using the hide_admin_menus() callback function.
  • The hide_admin_menus() callback function defines the logic of the code. It』s run every time the admin_menu action fires.
  • Inside the callback function, the current_user_can( ‘create_users’ ) function checks whether the logged-in user is an admin. Since only site admins have the create_user capability, the function ends with a return statement if the user is an admin.
  • The wp_get_current_user() WordPress function retrieves the current user object. With this function, we can check whether the logged-in user has a particular display_name set. This is an optional line, in case you want to omit certain non-admin users from being locked out due to this callback function.
  • The remove_menu_page() WordPress function removes top-level admin menus. In the code example above, I』m removing the following admin menus: Plugins, Themes, Tools, Users, Pages, and Options.

After saving the plugin file, here』s a snapshot of the WordPress dashboard with an admin logged in.

The default WordPress dashboard for all users

The default WordPress admin dashboard

And here』s a screenshot of the WordPress dashboard with a non-admin user logged in.

Hiding the sensitive admin menus to non-admin users using actions

Hiding sensitive admin menu items from non-admin users

This solution only hides the specified admin menu items from appearing in the WordPress dashboard. All users can still access them by entering the menu URLs in their browsers.

To disable certain user roles from accessing specific menus, you need to edit their capabilities.

Hooking a Filter

Filters provide a way for your custom code to modify data used by other WordPress functions. Unlike actions, functions hooked to filters need to return a value.

The add_filter() Filter Function

You can hook a callback function to a filter by following these steps:

  1. Define a Callback function that will run when WordPress fires the filter. Callback functions for filters need to have at least one argument specified, as all filters pass at least one value to their callback functions.
  2. Register the callback function to a filter with the add_filter() function. The filter will take care of calling the callback function. As per the WordPress Codex, the add_filter() function needs to pass at least two parameters:
    • Name of the filter to hook into.
    • Name of the callback function that』ll run when the filter fires.
  3. The add_filter() function also accepts two additional optional parameters for setting the priority and the number of arguments. These parameters work the same way as with the add_action() function.

Here』s an example of how you can use the add_filter() function to hook a callback function to a filter.

// define the filter callback function with at least one argument passed
// the number of arguments that you can pass depends on how the filter is defined
function filter_callback_function( $arg1, $arg2 ) {
    // make your code do something with the arguments and return something
    return $something;
}

// now hook the callback function to the ‘example_filter’
add_filter( ‘example_filter’, ‘filter_callback_function’, [priority], [no_of_args] );

// ’10’ is the default priority set for the callback function
// and ‘1’ is the default number of arguments passed
Example of Hooking a Filter

WordPress provides a filter called login_message to filter the message displayed on the login page above the login form. The value returned by this filter can have HTML markup.

Let』s hook into the login_message filter and modify the message shown on the login screen.

// show a custom login message above the login form
function custom_login_message( $message ) {
    if ( empty( $message ) ) {
        return “

Welcome to Let’s Develop by Salman Ravoof! Please log in to start learning.

“;
}
    else {
        return $message;
}
}
add_filter( ‘login_message’, ‘custom_login_message’ );

The if-else statement in the callback function checks whether the login message is already set, mostly by another plugin or theme. In such cases, the callback function returns the original value making no changes. This is one way to avoid conflicts with other plugins or themes.

You can see the message being displayed above the login form in the WordPress login page.

Showing a custom login message above the login form box

Showing a custom login message above the login form

You can style all the elements on the login page by enqueueing custom style sheets. Doing so will allow you to fully customize your default WordPress login page.

You』ll learn how to load custom style sheets using actions in the 「Customize the WordPress Login Page with Hooks」 section.

Finding Filters Supported by WordPress

Anywhere WordPress processes or modifies data, you can almost certainly find a filter to hook into and change it. Think of filters as an interface between the WordPress database and the browser.

You can find an exhaustive list of all the filters supported by WordPress in the Plugin API/Filter Reference page.

Filters reference page from the Plugin API section

WordPress provides a variety of filters to hook into

All the filters listed there are split up into multiple categories and arranged from top to bottom in the WordPress execution order.

If you want to find filters to hook into in the WordPress source code, perform a search for the term 「apply_filters」 and you』ll get tons of results. The WordPress Code Reference is also a great place to search for everything that』s included in WordPress, including actions and filters.

How WordPress Core Uses Filters

WordPress Core itself uses a lot of its built-in filters to modify data used by its various functions.

Consider the the_content filter for example. It filters post content after it』s retrieved from the database and before it』s displayed on the browser.

Just like with actions, you can find most of WordPress Core』s filter functions related to the the_content hook in the wp-includes/default-filters.php file.

Here』s a list of all the core add_filter() functions that hook into the the_content filter:

add_filter( ‘the_content’, ‘do_blocks’, 9 );
add_filter( ‘the_content’, ‘wptexturize’ );
add_filter( ‘the_content’, ‘convert_smilies’, 20 );
add_filter( ‘the_content’, ‘wpautop’ );
add_filter( ‘the_content’, ‘shortcode_unautop’ );
add_filter( ‘the_content’, ‘prepend_attachment’ );
add_filter( ‘the_content’, ‘wp_make_content_images_responsive’ );
add_filter( ‘the_content’, ‘do_shortcode’, 11 ); // AFTER wpautop().

Note the priority specified for certain callback functions.

For example, the do_blocks() function parses any dynamic blocks in the post content and re-renders them to be compatible with WordPress』 new block editor. It』s specified a higher priority than the default (10) to make sure that the content is block-ready before the other functions are run.

The convert_smilies() function is set to run at a lower priority as its task is to convert text smileys to image sprites. Having it run in the end after filtering all the post content makes sense.

Fun Fact: Shortcodes are a subset of filters. They take in input from the shortcode, process it, and then return the output back to it. Learn more about shortcodes in this ultimate WordPress Shortcodes guide.

Other Filter Functions

While add_filter() is the most used filter function, there are many other helpful filter functions. Let』s discuss them all in depth.

  • has_filter()

This function checks whether the specified filter is hooked by any function. It accepts two parameters. The first parameter is for entering the filter name. The second parameter is optional and is for entering the name of the callback function.

has_filter( ‘filter_name’, ‘function_to_check’ );

If you specify just the first parameter, it』ll return true if the filter_name is hooked by any function.

However, if you specify both the parameters, then it』ll return false if the callback function mentioned isn』t registered with the given filter. If it finds the callback function registered with the filter, then it』ll return the priority (an integer) set for that function on this filter.

One possible application of the has_filter() function is to check whether any filter has been hooked already, and based on that go ahead with code execution.

// check to see if ‘the_content’ filter has been hooked
if ( ! has_filter( ‘the_content’ ) {
    // hook the filter if and only if it hasn’t been hooked before
    add_filter( ‘the_content’, ‘modify_the_content’ );
}

  • apply_filters()

This filter function is like the do_action() action function. Any callback functions hooked to this filter will run wherever this function is in the WordPress code.

You can also use this function to create a new custom filter by specifying the filter name and the filter value as parameters.

apply_filters( ‘filter_name’, ‘value_to_filter’, [argument1], [argument2] );

Don』t forget to specify any additional arguments if you want to pass them on to your callback functions. Most filters only use one argument, so it』s easy to miss out on defining the additional ones.

  • apply_filters_ref_array()

This function is like the apply_filters() function, except all the arguments it accepts are bundled up as an array.

// an example array
$arguments_array = array( ‘some_value’, ‘foo’, false, ‘another_value’ );

apply_filters_ref_array( ‘example_filter’, $arguments_array );

This filter function can be handy when you have many arguments to pass or if all of them are already in an array. Ensure that the arguments inside the array are in the right order.

  • current_filter()

This filter function retrieves the name of the current filter or action being run. You don』t need to specify any parameters as it runs within the callback function.

Here』s an example of its usage:

function example_callback() {
    echo current_filter(); // ‘the_title’ will be echoed
    return
}
add_filter( ‘the_title’, ‘example_callback’ );

Despite its name, this function can retrieve the name of both actions and filters.

  • remove_filter()

This filter function removes the callback function attached to the specified filter. It』s works exactly like the remove_action() function. You can use it to delete default WordPress functions registered with a specific filter, and if necessary replace them with your own functions.

remove_filter( ‘filter_name’, ‘function_to_be_removed’, [priority] );

To unhitch a callback function hooked to a filter, the function_to_be_removed and priority parameters must be identical to the arguments used when hooking the callback function.

If the filter has been added from within a class, which is usually the case when they』re added by plugins, then you need to access the class variable to remove the filter.

// access the class variable first, and then remove the filter through it
global $some_class;

remove_filter( ‘the_content’, array($some_class, ‘class_filter_callback’) );

Let』s check out a great example of remove_filter() in action.

The WooCommerce plugin uses the wc_lostpassword_url() call function hooked to its lostpassword_url filter to redirect 「Lost Your Password?」 attempts by users.

It takes any user clicking on that link to a custom frontend page with the URL /my-account/lost-password. Without this filter, it』d take them to the standard WordPress login URL at /wp-login.php.

Say you want to reset this functionality and send your users to the default password retrieval page or to a separate page altogether. You can remove this callback function like this:

remove_filter( ‘lostpassword_url’, ‘wc_lostpassword_url’, 10 );

  • remove_all_filters()

This filter function removes all the callback functions registered to a filter.

remove_all_filters( ‘filter_name’, [priority] );

It』s similar to the remove_all_actions() function.

The popular Advanced Excerpts plugin uses this function to remove all default functions hooked to the_excerpt and get_the_excerpt filters. After doing that, it then hooks its own callback function to the filter.

// Ensure our filter is hooked, regardless of the page type
if ( ! has_filter( ‘get_the_excerpt’, array( $advanced_excerpt, ‘filter_excerpt’ ) ) ) {
    remove_all_filters( ‘get_the_excerpt’ );
    remove_all_filters( ‘the_excerpt’ );
    add_filter( ‘get_the_excerpt’, array( $advanced_excerpt, ‘filter_excerpt’ ) );
}

  • doing_filter()

This filter function checks whether the filter specified is being executed at the moment.

if ( doing_filter( ‘save_post’ ) ) {
    // run your code here
}

It returns a boolean value (true or false).

You should note the difference between this function and the current_filter() function, which returns the name of the filter or action being run (a string).

Filters Example 1: Adding a Profanity Filter for Comments

Managing all the comments on your WordPress site can be a cumbersome process. The comment_text filter lets you set up rules to modify the comments before they』re printed on the display.

Comments with dummy profane words which are still uncensored

Unfiltered comments with dummy profanities marked

You can direct WordPress to remove any expletives automatically before they』re displayed to your site visitors.讓我們開始吧。

// hook into the ‘comment_text’ filter with the callback function
add_filter( ‘comment_text’, ‘the_profanity_filter’ );

// define a callback function to filter profanities in comments
function the_profanity_filter( $comment_text ) {
    // define an array of profane words and count how many are there
    $profaneWords = array(‘fudge’, ‘darn’, ‘pickles’, ‘blows’, ‘dangit’);
    $profaneWordsCount = sizeof($profaneWords);
    
    // loop through the profanities in $comment_text and replace them with ‘*’
    for($i=0; $i < $profaneWordsCount; $i++) {         $comment_text = str_ireplace( $profaneWords[$i], str_repeat('*', strlen( $profaneWords[$i]) ), $comment_text );     }          return $comment_text; }

Here』s a line-by-line breakdown of the code:

  • comment_text is a filter hook that lets you modify the text of a comment before the browser displays it. You can register your callback function with it to filter its output.
  • The add_filter() function lets you hook into the comment_text filter and attach a callback function to it.
  • the_profanity_filter() is the name of the callback function. It accepts only one parameter, which is a string containing the comment text. Define this custom function with the appropriate code logic.
  • Store all the profane words in a PHP array called profaneWords. You can add as many words as you want to this array. I』m storing the size of this array in the profaneWordsCount variable with the help of sizeof() PHP function.
  • Loop through all the profane words and use PHP』s default str_ireplace() function to replace any of the matching profanities with * symbols. Since this is a case-insensitive string replacement function, you don』t have to worry about capitalization.
  • Use return to output the filtered comment text.

Save the changes to your custom plugin file and reload any post with comments. All the words you』ve included in the profaneWords array should now be replaced with 『*』 symbols.

Comments with dummy profane words which are all now censored

Censoring profanity in comments with 『*』 symbols

The original comments will still be available as is in the database. This filter only modifies the comment text before it』s outputted to the frontend.

The original comment stays unaltered in the site backend

The original comment on the site backend

Once you』re hooked into the right filter, you can do a lot of cool stuff with it.

For example, you can also use the comment_text filter to remove any URLs from all the comments (make sure to read this in-depth guide on how to stop spam comments in WordPress).

Or you can hook into the pre_comment_approved filter and mark comments as approved, spam, or thrash based on predefined criteria.

Filters Example 2: Insert Content After a Post

You』ve already seen how WordPress uses the_content filter to modify post or page content. Let』s use the same filter to add something at the end of each post.

// hook into ‘the_content’ filter with a callback function
add_filter( ‘the_content’, ‘insert_content_below’ );

// define the callback function to insert something below the post
function insert_content_below( $content ) {
    // check to see if we’re inside the main loop in a single post
    if ( is_single() && in_the_loop() && is_main_query() ) {
  return $content . 」

Let me insert myself here

I’ll appear after the post. You can insert anything here. Even HTML. Headers, links, images, scripts, I’ll take them all and append it to the end of the post content. You can also give me a class, so you can style me easily with CSS style sheets.

” ;
    }
    
    return $content;
}

Understanding the code logic in the above example:

  • the_content filter hook helps you grab the content of the current post and customize it.
  • Use the add_filter() function to hook into the_content filter with the insert_content_below() callback function.
  • Define the callback function by passing the current post』s content as a parameter ($content).
  • Inside the callback function, check that you』re only filtering the content in the main query, which in this case is the post content. If you don』t verify this, sometimes the code will unintentionally filter content from other places such as sidebars and footers.
  • is_main_query() and in_the_loop() conditionals determine whether the query is a main query and happening within the main WordPress Loop.
  • is_single() conditional checks whether the query is for a single post.
  • Use PHP』s string concatenation operator ($content . 「your additions」) to add extra stuff to the page content.
  • return the filtered comment if all the above conditionals check out. If it doesn』t, then just return the content with no changes.

Save your plugin file, load up any post on your site, and scroll to the end.

Additional content inserted after the post content

Inserting something at the end of the post content

You can use the same logic to add anything to the beginning of all your posts by reversing the position of string concatenation parameters (「your additions」 . $content).

Customize the WordPress Login Page with Hooks

Let』s use both actions and filters to customize the default WordPress login page. I』ll create a new plugin called Sal Custom Login Page to do this. You can find the full source code of this plugin at the end of this section.

Need a blazing-fast, secure, and developer-friendly hosting for your client sites? Kinsta在構建時就考慮了WordPress開發人員,並提供了許多工具和功能強大的儀錶板。查看我們的計劃

The final customized WordPress Login Screen

The final customized WordPress login screen

Let』s get started by adding the standard plugin header fields and registering it with WordPress.

First, hook into the login_enque_scripts action to enqueue your custom style sheet. Any scripts or styles you enqueue here are included in the header section of your login page.

If you want to load custom scripts and style sheets on your site』s frontend (rather than on the admin backend or login area), then you need to hook into the wp_enqueue_scripts action. You can read more about it in the WordPress Codex and Kinsta』s article on how to use wp_enqueue_scripts.

Inside the salhooks_login_stylesheet() callback function, use the wp_enqueue_style() function to load the custom style sheet (sal-custom-login-page-styles.css) placed in the same plugin』s directory. WordPress』 built-in plugin_dir_url( __FILE__ ) function makes it easy to get the URL path (with a trailing slash) of the current plugin』s directory.

I won』t explain the CSS styles applied here, but you can find them all in the source code linked at the end of this section.

// Custom login ERROR message to keep the site more secure
add_filter( ‘login_errors’, ‘salhooks_remove_login_errors’, 10 );
function salhooks_remove_login_errors() {
    return ‘Incorrect credentials. Please try again!’;
}

Next, hook into the login_errors filter to change the error message shown when someone enters incorrect credentials. Filtering the error message will block attackers from guessing your username easily.

// Remove the login form box shake animation for incorrect credentials
add_action( ‘login_head’, ‘remove_login_error_shake’ );
function remove_login_error_shake() {
    remove_action( ‘login_head’, ‘wp_shake_js’, 12 );
}

Every time someone enters incorrect login credentials, the login form box shakes aggressively. This is an optional step, but I』ve included it to show that you can also remove certain features from the login page.

You』ll learn more about remove_action() and remove_filter() functions in the final section of this article.

// Change the logo and header link above the login form
add_filter( ‘login_headerurl’, ‘salhooks_login_headerurl’);
function salhooks_login_headerurl( $url ) {
    $url=”https://salmanravoof.com”;
    return $url;
}

add_filter( ‘login_headertext’, ‘salhooks_login_headertext’);
function salhooks_login_headertext( $text ) {
    $text=”Salman Ravoof”;
    return $text;
}

The final step is to change the login header』s URL and text. You can hook into the login_headerurl and login_headertext filters to modify them both.

If you want to build upon this plugin and experiment further, you can download the plugin』s source code and get started.

WordPress Hooks List and Resources

It』s hard to memorize all the various hooks WordPress has. There are thousands of built-in actions and filters to hook into. Hence, finding an appropriate hook may sometimes feel like a scavenger hunt.

Thankfully, there are various resources you can use to identify the perfect hook for your needs.

  • WordPress Plugin Handbook — Hooks

The first place to get familiar with hooks is the WordPress Codex, particularly its Hooks section in the Plugin Handbook. Here you can find essential information about hooks and links to complete documentation on all actions and filters.

WordPress Hooks section in the Plugin Handbook

Start learning Hooks with the WordPress Plugin Handbook

Bookmark these helpful links from the Plugin Handbook to speed up your search:

  • Plugin API — Hooks Function Reference
  • Plugin API — Action Reference
  • Plugin API — Filter Reference

Both the action reference and the filter reference pages will give you a list of all the hooks that typically run during a specific WordPress request.

For example, you can find all the hooks fired when you access an admin page, when you』re dealing with post page attachments, or with categories.

  • WordPress Code Reference

The WordPress Codex also includes a handy search tool to find all its functions, hooks, methods, and classes. This page also lists new and updated components in the most recent version of WordPress. Head here first if you want to find what』s happening inside WordPress.

WordPress Code Reference search tool in WordPress Codex

Search for anything inside WordPress here

  • Adam R Brown』s WordPress Hooks Index

This index of WordPress hooks sorts all the hooks by type, the WordPress version they debuted, and if they』re deprecated.

Adam R Brown's WordPress Hooks Index

Adam R Brown』s WordPress Hooks Index

Sorting the hooks in order of their appearance will show you that the oldest WordPress hooks are still the most used ones. If you』re new to WordPress development, getting familiar with these popular actions and filters is the fastest way to catch up.

While this index hasn』t been updated since WordPress 5.1, it』s still helpful to skim through all the major hooks.

Still finding it hard to find the hook you want? An online search with the right keyword is always a good way to start. If everything else fails, you can always dig into the WordPress code.

Finding Hooks Registered on a WordPress Page

As we』ve seen, WordPress has tons of hooks available, but not every hook fires on every page. If you can find which actions and filters you can hook into on a particular page, then you』ve won half the battle.

While you can use advanced PHP debugging tools like xdebug and PHPCS to help with this, there are simpler development tools like Debug Bar and Query Monitor which you can run inside WordPress.

Debug Bar with Actions and Filters Add-On

Debug Bar is an official WordPress plugin that adds a Debug menu to your admin bar. It shows PHP warnings and notices, cache requests, MySQL queries, and other helpful debugging information.

Info

This plugging hasn』t been recently updated, nor tested with the latest major releases of WordPress. We』re mentioning it as a handy plugin to learn more about WordPress hooks. Use it on a staging environment.

The WordPress Debug Bar WordPress plugin

The WordPress Debug Bar WordPress plugin

After installing the plugin, you need to add the code snippet below to your site』s wp-config.php file to enable its debugging features.

define( ‘WP_DEBUG’, true ); // tracks PHP Warnings and Notices
define( ‘SAVEQUERIES’, true ); // tracks and displays MySQL queries

You should now see the Debug menu option show up in your admin bar. Clicking on it will take you to its dashboard where you can see various queries and caches attached to the page you accessed it from.

Showing the Debug menu in the admin bar

The 『Debug』 menu in the WordPress admin bar

Next, you need to install the Debug Bar Actions and Filters Addon plugin. It』s a handy extension that』ll add two more tabs to your Debug Bar dashboard to display actions and filters triggered on the current request.

Action Hooks panel inside the Debug Bar dashboard

Actions listed in their loading order for the current page

It』ll also list all the functions hooked to them with their priority.

Debug Bar plugin with the Actions and Filters Addon installed

Filters listed with their priority and registered callback functions

You can click on the Debug menu from any page on your site to know all the actions and filters that you can hook into on that page.

Query Monitor

Query Monitor is a powerful developer tools panel for WordPress. You can use it to dig into the hooks available on a page and their load order.

Query Monitor WordPress plugin

Query Monitor WordPress plugin

Unlike with Debug Bar, you don』t have to install any addons to see the actions and filters triggered on a certain page.

Access Query Monitor from the admin bar

You can access Query Monitor from the admin bar

Query Monitor also gives you more information about where exactly a hook is being fired from.

The Hooks & Actions panel in Query Monitor

The Hooks & Actions panel in Query Monitor

In the component column, you can see that most of the hooks are registered from the Core. But some hooks are registered from a theme or plugin. A few hooks may be registered from more than one component.

You can use the hook and component dropdown menus to view only the hooks you need.

Note: Query Monitor uses 「Hooks」 as a catchall term for both actions and filters, but it calls the registered callback functions as 「Actions.」 This is technically a wrong definition and can confuse you, so do keep that in mind.

You can do more than just check all the queries and requests with Query Monitor. It also includes advanced features such as listing styles, scripts, languages, Ajax calls, user capability checks, and REST API Calls.

The 「all」 Hook

WordPress has a special hook named 『all』 that you can hook in to run a callback function for every single hook, regardless of whether it』s registered with them all. It』s useful to debug page crashes or if you want to know when a particular event is happening.

For instance, you can use the all hook like in the example below to echo all the actions being run.

// echo all the actions being run
function debug_helper_function(){
    echo ‘

‘ . current_action() . ‘

‘;
}
add_action( ‘all’, ‘debug_helper_function’ );

The debug_helper_function() defined above will run when any action fires. Knowing what the last run action was will give you a better idea of where you need to look into.

Where Are WordPress Hooks Stored?

WordPress uses the WP_Hook class to implement how hooks work. This core class is used to handle all the inbuilt WordPress actions and filters. You can find almost all the code related to this class in the wp-includes/class-wp-hook.php file.

Technically, the WP_Hook class is an array of objects comprising properties such as callbacks, iterations, current_priority, nesting_level, and doing_action. It also defines a lot of useful hook functions which can be called using the WP_Hook methods.

Most WordPress developers don』t have to worry much about where WordPress stores hooks as long as they stick to the Plugin API guidelines.

There are two types of WordPress hooks: actions and filters, and this guide breaks down exactly when (and how!) to use each one ?

點擊鳴叫

How to Create Your Custom WordPress Hooks

You』ve seen the various hooks WordPress provides through its Plugin API. You』ve also looked at how you can use the default hooks to inject your own code into WordPress runtime.

If you』re a plugin or theme developer, it』s good practice to provide other developers with a way to interact with your code the same way. Custom hooks let you do exactly that. They allow other developers to extend and modify the functionality of your plugins and themes.

Creating your own actions and filters is fairly simple. You use the same functions WordPress Core uses to create hooks. Let』s look at a few examples.

How to Create Custom Actions in WordPress

Use the do_action() function to create a custom action hook.方法如下:

// the position where you insert your action is where it’ll run when called
do_action( ‘ my_unique_custom_action’ );
// continue with the rest of your code

Now, other developers can hook into your plugin or theme without modifying the source code. All they have to do is register their callback functions to your plugin』s custom action using the add_action() function.

add_action( ‘my_unique_custom_action’, ‘some_callback_function’ );

// define the callback function you mentioned in the above action function
some_callback_function() {
     // this code will run wherever your custom action hook is
}

Make sure to document your custom hooks thoroughly, explaining what they do in detail. After all, the main use of creating custom hooks is to help other developers interact with your code.

How to Create a Custom Filter in WordPress

Use the apply_filters() function to create a custom filter hook. Here』s how you can do it:

$value_to_filter = “I’m a string, but this can be any PHP data type”;

// filters modify a value and are typically tied to a predefined variable
apply_filters( ‘my_custom_filter’, $value_to_filter );

Your custom filter』s parameters should include a unique identifier and a value to filter. Other developers can hook into your custom filter with the add_filter() function and modify the passed value.

add_filter( ‘my_custom_filter’, ‘some_callback_function’ );

// define the callback function you mentioned in the above filter function
function some_callback_function( $value_to_filter ) {
    // modify the passed value (or not)
    return $value_to_filter; // returning a value is a must for filters
}

When you』re defining your custom filter, ensure that it』s not positioned before the value it』s supposed to filter is defined. If you don』t position the filter correctly, the filtered value will get overwritten by the default value afterward.

Custom Hooks Naming Convention

It』s important to choose a unique name for all your custom hooks. Since any plugin or theme can have its own custom hooks, having identical hook names can cause code collisions with unexpected results.

For example, if you name your action send_email, it』s highly likely that other plugin developers may also choose the same term as it isn』t unique enough. If any website installs both yours and the other developer』s plugins, it can cause errors that』ll be hard to trace.

You can prefix all your custom hooks with a common identifier to keep them both simple and unique. So, instead of send_email, you can name it plugin_name_send_email (plugin_name_ is the unique prefix here).

Custom Hooks Demo with an Extensible Plugin

Let』s create an extensible plugin (or a pluggable plugin) that will allow other developers to interact with it using its custom hooks.

I』ll name this plugin Custom Hooks Demo. Its main function is to output a quotation box wherever you insert a shortcode. It』ll include custom actions and filters at the right locations to make it possible for other developers to modify or extend its functionality.

You can refer to my WordPress shortcodes guide to learn more about how shortcodes work.

Let』s get started with the extensible plugin.

“;
    echo $quote_content;
    echo “

“;
    echo “― ” . $quote_author . ““;
    echo “

“;
    
    // set an action hook to run after you output everything
    do_action( ‘the_ending_custom_action’ );
    
    return ob_get_clean(); // get buffer contents, delete the buffer, and then stop buffering
}

  • The add_shortcode() function is used to create the custom shortcode. And then you define the shortcode』s callback function with all of this plugin』s functionality.
  • ob_start() is a PHP function that enables output buffering. It』s a super handy feature that instructs PHP to hold onto any output in the server』s buffer memory rather than outputting it right away. You can use it to build complex, readable HTML code in PHP.
  • do_action( ‘the_topmost_custom_action’ ) defines your first custom action. To make it useful, you need to define it before the plugin outputs anything. Other developers can hook into this custom action to run their code before this custom shortcode prints out anything.
  • Create the variables you want to filter. In this plugin, those variables are $quote_content and $quote_author. They』re both strings in this example, but you can set them to be any PHP data-type (e.g. integer, boolean, array).
  • Use the apply_filters() function to create your custom filters. Since all filters return a value, you can assign the previously defined variables to this filter』s returned value. Other developers can now hook into this filter to modify the default values of the predefined variables.
  • Use echo statements to build your shortcode』s output line-by-line. Since we』ve enabled output buffering, no output will reach the browser right away.
  • do_action( ‘the_ending_custom_action’ ) defines your last custom action. You need to define it at the very end, but before returning all the buffer contents.
  • ob_get_clean() is an default 3-in-1 PHP function. It』ll retrieve the buffer contents, eliminate all the buffer data, and then stop the output buffering. It』ll return the collected buffer contents as a single concatenated string.

Once saved and activated, adding the [custom_hooks_demo] shortcode to your post content will output a quotation box with the default values.

The original quotation box as outputted by the shortcode defined in the Custom Hooks Demo plugin

The original quotation box using the Custom Hooks Demo plugin

Now, let』s create another plugin called Custom Hooks Demo Extension. It』ll hook into all the custom hooks created by the previous plugin and do or modify something.

‘;
}

/ **
 * add a button below the shortcut output by hooking into the ‘the_ending_custom_action’
* /
add_action( ‘the_ending_custom_action’, ‘add_button_callback’ );
function add_button_callback() {
    echo ‘

‘;
}

As you can see, this extension plugin contains nothing but action and filter functions hooking into the original plugin at the right places to make modifications.

It uses the add_action() and add_filter() functions to register its callback functions with the custom actions and filters created by the original plugin (e.g. the_topmost_custom_action, custom_quote_author).

The modified quotation box after the extension plugin changes the original output

The extension plugin modifies the original quotation box

Custom action hooks allow you to interject your code at the right intervals in the original plugin and run your own scripts. Here, we』re adding an image at the top and a button at the bottom.

Likewise, custom filter hooks let you modify the values of the quote content and its author name. The ultimate outcome is a plugin that』s fully extensible by anyone without modifying its source code.

Working With Custom Hooks from Third-Party Developers

Custom hooks enable individual WordPress plugins and themes to have a rich ecosystem of extensible plugins. Consider the WooCommerce plugin. It adds ecommerce functionality to WordPress, but it also includes tons of hooks within its code.

WooCommerce Hook Reference

WooCommerce Action and Filter Hook Reference

WooCommerce has hundreds of extensions and plugins that use its hooks to build on its core functionality and make it even better.

You can use these extensions to integrate WooCommerce with Stripe, MailChimp, Salesforce, Zapier, and much more.

WooCommece's page on its most popular extensions

Extensions extend WooCommerce』s functionality

A good practice is to check out the documentation section of popular WordPress plugins to see how they implement custom hooks. A few of my top suggestions are Easy Digital Downloads, BuddyPress, Quiz and Survey Master, and Gravity Forms.

When to Use Custom Hooks?

Depending on the theme or plugin you』re creating, and who it』s intended for, you may wonder whether you need to add any custom hooks.

A good rule of thumb when deciding on whether or not to add custom hooks is to check if they offer any extensibility benefits to other developers. If not, then it』s better to hold off until other developers ask you to add them.

You need to be highly certain about adding custom hooks to your plugin or theme. Once it』s released, and if other developers have already used it, you can』t ever change it without breaking backward compatibility.

Removing Callback Functions from WordPress Hooks

You』ve already seen examples of how to remove callback functions registered to certain hooks. These callbacks could be registered by plugins, themes, or even WordPress Core itself. Let』s look at removing hooked callback functions with more examples.

To remove a callback function from a hook, depending on whether it』s registered to an action or a filter, you need to use the remove_action() or remove_filter() functions.

One caveat is that you need to call these functions with the identical parameters used to register the callback function. Basically, copy-paste the parameters from their add_action() or add_filter() functions.

Also, you can remove callback functions only after they』re registered. If you try to remove them before they』re registered, the removal process will fail. You need to get the execution order of the hooks right.

Let』s say you want to remove a callback function registered by a theme that adds bloat to your site (you want a fast site, don』t you?).

function wp_bloated_callback_function() {   
// some code that adds a lot of bloat to the site
}
add_action( ‘template_redirect’, ‘wp_bloated_callback_function’, 5 );

For example, the above callback function could load many unnecessary scripts and style sheets. Removing it will give your site a huge performance boost.

However, you need to ensure that the remove_action() function runs only after the template_redirect action. One way to do this is to hook into the after_setup_theme action as it』s triggered after the template_redirect action.

function wp_remove_bloat() {
    // ensure all parameters are identical to the original add_action() function
    remove_action( ‘template_redirect’, ‘wp_bloated_callback_function’, 5 );
}

// ensure that remove_action() is called only after add_action()
add_action( ‘after_setup_theme’, ‘wp_remove_bloat’ );

The wp_bloated_callback_function() will now unhitch itself from the template_redirect action.

Special Cases for Removing Callback Functions

There』s more to removing callback functions than just disabling them altogether. Sometimes you may need to remove them temporarily, run your code, and then add them again.

For example, the save_post action fires every time the wp_insert_post() and wp_publish_post() functions are called. You can find them both defined in the wp-includes/post.php file.

So, if you have a callback function hooked to the save_post action, and if you call wp_insert_post() or wp_publish_post() functions within your callback function, the save_post action will fire multiple times.

function some_callback_function( $post_id, $post ) {
    // do something here
    wp_insert_post( [some_array] ); // this function also calls the ‘save_post’ action
    // maybe do something more
}
add_action( ‘save_post’, ‘some_callback_function’, 10, 2 );

A function calling the action which also calls it can create unexpected results. One way to get around this issue is to use the remove_action() function inside your callback function before you call wp_insert_post().

function some_callback_function( $post_id, $post ) {
    // do something here

    // remove the callback function from the 『save_post』 action
    remove_action( ‘save_post’, ‘some_callback_function’, 10, 2 );

    // now run the wp_insert_post() function
    wp_insert_post( [some_array] );

    // add the callback function back to the 『save_post』 action
    add_action( ‘save_post’, ‘some_callback_function’, 10, 2 );

    // maybe do something more
}
add_action( ‘save_post’, ‘some_callback_function’, 10, 2 );

That』s another practical use of remove_action() or remove_filter() functions. Digging deeper into the WordPress Core will help you understand how you can avoid these situations better.

Bonus WordPress Hooks Tutorials

  • Manually Add Code to WordPress Header and Footer
  • Your Complete Guide to the WordPress Media Library
  • How to Create and Modify a WordPress Cron Job
  • How to Create a WordPress Child Theme
  • Disable WordPress Plugins From Loading on Specific Pages and Posts
  • Disable Emojis in WordPress with Code

WordPress Hooks are one of the most important tools to have in a WordPress developer』s arsenal. ? Learn the difference between actions and filters (and how to use them) in this guide!

點擊鳴叫

摘要

There are multiple advantages of using WordPress hooks if you』re a WordPress developer.

Not only do hooks allow you to modify or extend the core functionality of WordPress, but you can also use them to modify plugins, themes, and let other developers interact with your plugins or themes.

It』s time to get hooked on WordPress hooks!

如果您喜歡這篇文章,那麼您會喜歡Kinsta的WordPress託管平台。加速您的網站並獲得我們經驗豐富的WordPress團隊的24/7支持。我們基於Google Cloud的基礎架構專註於自動擴展,性能和安全性。讓我們向您展示Kinsta的與眾不同!查看我們的計劃

相關文章