2015-10-06 15 views
1

我使用WordPress Sage Starter主題(https://roots.io/sage/)。它使用名稱空間來進行函數聲明。使用函數作爲用名稱空間聲明的另一個函數的回調

我在我的lib/extras.php文件中有一個函數(my_function_comments)來修改註釋標記。這個文件有這個名字空間:namespace Roots \ Sage \ Extras; 現在我需要使用該函數作爲回調的另一個文件模板/ comments.php了,因爲這:

<?php wp_list_comments(array('style' => 'ol', 
          'short_ping' => true, 
          'avatar_size' => 60, 
          'type' => 'comment', 
          'callback' => 'my_function_comments', 
         )); ?> 

當然,my_function_comments是不會在這個文件,所以我編寫調用這樣wp_list_comments:

<?php use Roots\Sage\Extras; ?> 
<?php wp_list_comments(array('style' => 'ol', 
          'short_ping' => true, 
          'avatar_size' => 60, 
          'type' => 'comment', 
          'callback' => 'Extras\my_function_comments', 
         )); ?> 

好吧,回調函數顯然是錯誤的,但我不知道如何編寫它來正確調用它。

也許有人可以幫助我弄清楚這一點。

謝謝!

PS。命名空間相關文檔可在此找到(命名空間部分):https://roots.io/upping-php-requirements-in-your-wordpress-themes-and-plugins/。也許這將有助於回答我的問題。

+1

函數與名稱空間聲明,只有類(及其方法)無關。如果你包含函數所在的文件,並且它在全局範圍內,那麼它是可訪問的。但如果它是一種方法,那麼你應該看到它的可訪問性屬性(如果是靜態的,那麼'Extras \ Class :: my_function_comments',否則,'Extras \ Class-> my_function_comments') –

+1

在回調中使用完整的命名空間串)。當wordpress執行回調時,命名空間是必需的,而不是在聲明它時。您可以使用'use'省略該行。 – WeSee

+0

謝謝你們兩位!我會嘗試發佈解決方案。謝謝! –

回答

1

正如@Wesee在評論中所說的,將函數用作回調的方式是將整個路徑放到函數中。於是我刪除這一行:

<?php use Roots\Sage\Extras; ?> 

並用它來打電話wp_list_comments:

<?php wp_list_comments(array('style' => 'ol', 
         'short_ping' => true, 
         'avatar_size' => 60, 
         'type' => 'comment', 
         'callback' => 'Roots\Sage\Extras\my_function_comments', 
        )); ?> 

謝謝你們!

相關問題