Polylang: How to translate custom strings?

自古美人都是妖i 提交于 2019-12-03 15:48:33
drazewski

You must first register all these strings for translation.

For example you echo "Hello world" in some template file like this:

<?php pll_e('Hello world'); ?>

To show string in the "Strings translation" add in your functions.php:

add_action('init', function() {
  pll_register_string('mytheme-hello', 'Hello world');
});

Add all custom strings you want to translate to this function.

As Polylang docs says it's good to check polylang functions for existance first - so site will not break upon Polylang plugin update - because it removes old files first.

So i propose this approach: in functions.phpfor theme of in your plugin's file, you can create wrappers for needed Polylang functions with fallbacks if polylang was removed, or updated so WP will not crash with undefined function error.

/**
 * Outputs localized string if polylang exists or  output's not translated one as a fallback
 *
 * @param $string
 *
 * @return  void
 */
function pl_e( $string = '' ) {
    if ( function_exists( 'pll_e' ) ) {
        pll_e( $string );
    } else {
        echo $string;
    }
}

/**
 * Returns translated string if polylang exists or  output's not translated one as a fallback
 *
 * @param $string
 *
 * @return string
 */
function pl__( $string = '' ) {
    if ( function_exists( 'pll__' ) ) {
        return pll__( $string );
    }

    return $string;
}

// these function prefixes can be either you are comfortable with.

NOTE we've created functions with single l in pl__ and pl_e and original Polylang functions are pll__ and pll_e.

These will be used in your theme to output or return translated strings.

And as mentioned before we must register these strings so Polylang will know that these should be translated.

If you work with theme probably it's good to initialize them in after_setup_theme hook like this:

function your_prefix_after_setup_theme() {

   // register our translatable strings - again first check if function exists.

    if ( function_exists( 'pll_register_string' ) ) {

        pll_register_string( 'ToggleNavigation', 'Toggle navigation', 'YourThemeName', false );

        pll_register_string( 'ToggleSearch', 'Toggle Search', 'YourThemeName', false );

        pll_register_string('404Message', 'It looks like nothing was found. Try getting back to the <a href="%s">home page</a>.', 'YourThemeName', true);

    }
}
 add_action( 'after_setup_theme', 'your_prefix_after_setup_theme' );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!