問題描述

我想在以下過濾器中修改 $ path 。它有 1 個輸入和 2 個參數。

function documents_template( $template = '' ) {

       $path = DOCUMENTS_INCLUDES_DIR . '/document/' . $template;

  return apply_filters( 'document_template', $path, $template );
}

這是我添加過濾器的功能,它會收到錯誤消息,如何獲得正確的?

function my_template( $template = '' ){

      $path = MY_INCLUDES_DIR . '/document/'. $template;

     return $path;
}
add_filter( 'document_template','my_template', 10, 2 );

我試圖改變我的返回值如下,它也不工作:

return apply_filters( 'my_template', $path, $template);

有了下面的答案,我的新過濾器仍然不能正常工作,那也許是因為我的過濾器是在一個類中?這裏是全新的代碼:

Class My_Class{
  function __construct() {
     add_filter( 'document_template', array( $this, 'my_template',10, 2 ) );
  }
 function my_template( $path, $template ){

      $path = MY_INCLUDES_DIR . '/document/'. $template;

     return $path;
 }
}

最佳解決辦法

function my_locate_template( $path, $template ){

      $path = MY_INCLUDES_DIR . '/document/'. $template;

     return $path;
}
add_filter( 'documents_template','my_locate_template', 10, 2 );

add_filter 需要 4 個變量。第一和第二是必需的。 1. 名稱的過濾器,2. 名稱的功能。第三個是優先級 (功能什麼時候被觸發) 。第四是參數的數量。如果你定義參數的數量,你也必須把它們放在你的函數中。例如,

add_filter( 'the_filter','your_function', 10, 1 );
function your_function($var1) {
   // Do something
}

如果過濾器支持更多的參數 (在這種情況下為 3)

   add_filter( 'the_filter','your_function', 10, 3 );
    function your_function($var1, $var2, $var3) {
       // Do somthing
    }

閲讀有關 add_filter()信息的所有代碼


function documents_template( $template = '' ) {

       $path = DOCUMENTS_INCLUDES_DIR . '/document/' . $template;

  return apply_filters( 'document_template', $path, $template );
}

function my_template( $path, $template ){

      $path = MY_INCLUDES_DIR . '/document/'. $template;

     return $path;
}
add_filter( 'document_template','my_template', 10, 2 );

此代碼適用於我。你嘗試過嗎


在你班上的改變:

add_filter( 'document_template', array( $this, 'my_template',10, 2 ) );

至:

add_filter( 'document_template', array( $this, 'my_template'), 10, 2  );

次佳解決辦法

這些需要匹配,但不要:

apply_filters( 'document_template', $path, $template );

add_filter( 'documents_template','my_template', 10, 2 );

document_template!= documents_template

否則,一切看起來都正確。

Edit

等等,不是一切都看起來正確。我不認為你想添加一個參數到你的回調函數定義。相反,您需要在回調中定義 $template,或者簡單地將其傳遞迴未修改。所以,替換這個:

function my_template( $template = '' ){

… 有了這個:

function my_template(){

例如。:

function my_template(){

      $path = MY_INCLUDES_DIR . '/document/'. $template;

     return $path;
}
add_filter( 'documents_template','my_template', 10, 2 );

編輯 2

好的,我的小錯誤。嘗試這樣做回調:

function my_template( $path, $template ){

      $path = MY_INCLUDES_DIR . '/document/'. $template;

     return $path;
}
add_filter( 'documents_template','my_template', 10, 2 );

參考文獻

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