Do Not Use Variables as Text Domains in WordPress

我之前都是照著 WordPress Plugin Boilerplate 的格式去製作 WordPress plugin。它的 text domain 是這樣寫的:

__( 'Translate me.', $text_domain );

但是當我透過 PHP_CodeSniffer 套用 WordPress coding standards 之後,這樣的用法卻被 sniffer 抓了出來並建議我修改。我稍微查了一下原因,發現在官方文件裡就已經有建議了:

Do not use variable names or constants for the text domain portion of a gettext function. For example: Do not do this as a shortcut:

__( 'Translate me.' , $text_domain );

Plugin Developer Handbook

至於不建議的理由,很多人都有寫過評論或文章來說明。雖然對於網站本身沒有影響,但是在使用 WP-CLI 建立語言檔時,不會執行 PHP code,只是 extract strings 而已,所以寫成變數的 $text_domain 就只會被視為單純的字串,不會被代換成變數的內容

As mentioned before, that command looks for all instances of __() and the like in your plugin to extract translatable strings. During that process, the code isn’t executed, but only parsed. That means it has no idea what the value of $text_domain is in __( 'Translate me', $text_domain ). It just knows that it’s a variable.

The Text Domain in WordPress Internationalization

雖然文章裡提到使用 Poedit 時也可能會遇到類似的問題,不過就我使用 Poedit 的經驗來看倒是沒有遇過呢?