钩子文档

gettext

💡 云策文档标注

概述

gettext 是一个 WordPress 过滤器钩子,用于过滤翻译后的文本。它由国际化函数(如 __()、_e() 等)调用,允许开发者修改翻译内容。

关键要点

  • gettext 过滤器应用于翻译后的文本,参数包括 $translation(已翻译文本)、$text(原始文本)和 $domain(文本域)。
  • 此过滤器始终运行,即使国际化未启用或文本域未加载,可能导致性能问题,需谨慎使用。
  • 对于单数/复数翻译函数(如 _n()),应使用 ngettext();对于上下文相关翻译函数(如 _x()),应使用 gettext_with_context() 和 ngettext_with_context()。

代码示例

add_filter( 'gettext', 'wpdocs_translate_text', 10, 3 );
function wpdocs_translate_text( $translated_text, $untranslated_text, $domain ) {
    if ( 'blah' !== $domain ) {
        return $translated_text;
    }
    // 在 'blah' 域内检查并修改字符串
}

注意事项

  • 由于 gettext 过滤器运行频繁(例如,在安装常见插件时每页可能运行数千次),应避免不必要的操作以优化性能。
  • 建议在函数中尽早检查文本域,如果不是目标域则立即返回,减少开销。
  • 避免在过滤器内执行重复的字符串替换或条件检查,以免累积性能影响。

📄 原文内容

Filters text with its translation.

Parameters

$translationstring
Translated text.
$textstring
Text to translate.
$domainstring
Text domain. Unique identifier for retrieving translated strings.

More Information

This filter hook is applied to the translated text by the internationalization functions (<a href="https://developer.wordpress.org/reference/functions/__/">__()</a>, <a href="https://developer.wordpress.org/reference/functions/_e/">_e()</a>, etc.).

IMPORTANT: This filter is always applied even if internationalization is not in effect, and if the text domain has not been loaded. If there are functions hooked to this filter, they will always run. This could lead to a performance problem.

For singular/plural aware translation functions such as <a href="https://developer.wordpress.org/reference/functions/_n/">_n()</a>, see <a href="https://developer.wordpress.org/reference/hooks/ngettext/">ngettext()</a>.

For context-specific translation functions such as <a href="https://developer.wordpress.org/reference/functions/_x/">_x()</a>, see filter hook gettext_with_context() and <a href="https://developer.wordpress.org/reference/hooks/ngettext_with_context/">ngettext_with_context()</a>.

Source

$translation = apply_filters( 'gettext', $translation, $text, $domain );

Changelog

Version Description
2.0.11 Introduced.

User Contributed Notes

  1. Skip to note 8 content

    This filter is ideally avoided as the performance aspect can be huge. If you do need it, be aware with a common suite of plugins installed this can easily run thousands of times on one page! WooCommerce and similar make everything translatable.

    It’s far improved to check the domain right away and return the translation instantly if it’s not the domain you’re wanting to translate. This minimises the overhead, rather than some of these examples that are running str_replace(), is_single() etc over and over unnecessarily which adds up due to the sheer quantity of times this code will run.

    add_filter( 'gettext', 'wpdocs_translate_text', 10, 3 );
    function wpdocs_translate_text( $translated_text, $untranslated_text, $domain ) {
    	if ( 'blah' !== $domain ) {
    		return $translated_text;
    	}
    
    	// Now do your checking for your string within the 'blah' domain
    }

  2. Skip to note 9 content

    Change the “Register” text on the WordPress default login page.

    add_action( 'login_head', 'default_login_page_head' );
    
    /**
     * Customise the login form using login_head.
     */
    function default_login_page_head() {
    	add_filter( 'gettext', 'change_login_form_register_keyword');
    }
    /**
      * Change Register text from the bottom of login form.
      *
      * @param $text string 
      * @return $text string
      * * * * * * * * * * * * * * * * * * */
    function change_login_form_register_keyword( $text ) {
    
    	$text = str_ireplace( 'Register',  'Sign Up',  $text );
        return $text;
    }

  3. Skip to note 10 content

    Change the Comment Form

    Change the default field names of the comment form. Assumes the current form includes field names “Name” and “Email” and that ‘theme_text_domain’ is the name of your theme’s text domain.

    add_filter( 'gettext', 'theme_change_comment_field_names', 20, 3 );
    /**
     * Change comment form default field names.
     *
     * @link <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext" rel="nofollow ugc">https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext</a>
     */
    function theme_change_comment_field_names( $translated_text, $text, $domain ) {
    
        if ( is_singular() ) {
    
            switch ( $translated_text ) {
    
                case 'Name' :
    
                    $translated_text = __( 'First Name', 'theme_text_domain' );
                    break;
    
                case 'Email' :
    
                    $translated_text = __( 'Email Address', 'theme_text_domain' );
                    break;
            }
    
        }
    
        return $translated_text;
    }

  4. Skip to note 11 content

    Remove Text from Admin Form

    add_filter('gettext', 'remove_admin_stuff', 20, 3);
    /**
     * Remove the text at the bottom of the Custom fields box in WordPress Post/Page Editor.
     *
     * @link <a href="https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext" rel="nofollow ugc">https://codex.wordpress.org/Plugin_API/Filter_Reference/gettext</a>
     */
    function remove_admin_stuff( $translated_text, $untranslated_text, $domain ) {
    
        $custom_field_text = 'Custom fields can be used to add extra metadata to a post that you can <a href="<a href="https://codex.wordpress.org/Using_Custom_Fields&quot" rel="nofollow ugc">https://codex.wordpress.org/Using_Custom_Fields"</a>; target="_blank">use in your theme</a>.';
    
        if ( is_admin() && $untranslated_text === $custom_field_text ) {
            return '';
        }
    
        return $translated_text;
    }

  5. Skip to note 12 content

    add_filter( 'gettext', 'wpdocs_change_login_form_register_keyword' );
    
    /**
      * Change Register link text on the login form
      *
      * @param $text string 
      * @return $text string
      * * * * * * * * * * * * * * * * * * */
    function wpdocs_change_login_form_register_keyword( $text ) {
     
        $text = str_ireplace( 'Register', 'Sign Up Now', $text );
    
        return $text;
    }

  6. Skip to note 13 content

    Change Text in Custom Post Admin Form

    add_filter('gettext', 'change_admin_cpt_text_filter', 20, 3);
    /*
     * Change the text in the admin for my custom post type
     * 
    **/
    function change_admin_cpt_text_filter( $translated_text, $untranslated_text, $domain ) {
    
      global $typenow;
    
      if( is_admin() && 'MY_CPT' == $typenow )  {
    
        //make the changes to the text
        switch( $untranslated_text ) {
    
            case 'Featured Image':
              $translated_text = __( 'NEW FEATURED IMAGE TEXT','text_domain' );
            break;
    
            case 'Enter title here':
              $translated_text = __( 'NEW TITLE COPY','text_domain' );
            break;
            
            //add more items
         }
       }
       return $translated_text;
    }

  7. Skip to note 14 content

    add_filter( 'gettext', 'wpdocs_change_login_form_register_keyword' );
    /**
      * Change Register success after text message.
      *
      * @param $text string 
    
      * @return $text string
      * * * * * * * * * * * * * * * * * * */
    function wpdocs_change_login_form_register_keyword( $text ) {
    
        $text = str_ireplace( 'Registration complete. Please check your email, then visit the', ' Custom Message',  $text );
    
        return $text;
    }