从 WordPress 中的模板上传翻译文件(.mo 和 .po)

Upload the translation file from the template in WordPress (.mo and .po)

提问人:Benjamin 提问时间:11/4/2023 最后编辑:Benjamin 更新时间:11/4/2023 访问量:46

问:

我想在 functions.php 文件中放置一个函数,以便在用户激活模板时,所有扩展名为 .mo.po 的文件都会复制到该路径中。wp-content\languages\themes

为此,我使用了以下不起作用的代码:

function load_the_languages() {
 load_theme_textdomain( 'themePro', get_template_directory() . '/languages' );
}
add_action( 'after_setup_theme', 'load_the_languages' );

我用来编写上述函数的源代码:

load_theme_textdomain()

请帮助我创建一个可以将所有扩展名为 .mo.po 的文件复制到 path 的函数。wp-content\languages\themes

经过大量搜索,我想出了上面的代码,我希望有更好的方法可以做到这一点。

提前感谢您的任何帮助。

php wordpress 函数 po mo

评论


答:

1赞 TSCAmerica.com 11/4/2023 #1

函数 () 用于加载主题的翻译文件,但它实际上不会将文件复制到其他位置。如果要将 .mo 和 .po 文件从主题目录复制到激活主题时,可以使用钩子,该钩子会在主题 iss 切换后触发。load_theme_textdomainlanguageswp-content/languages/themes directoryafter_switch_theme

function copy_language_files_to_global_directory() {
    $source_directory = get_template_directory() . '/languages';
    $destination_directory = WP_CONTENT_DIR . '/languages/themes';

    if (!is_dir($destination_directory)) {
        wp_mkdir_p($destination_directory);
    }

    // Copy .mo and .po files
    foreach (glob($source_directory . '/*.{mo,po}', GLOB_BRACE) as $file) {
        $destination_file = $destination_directory . '/' . basename($file);
        if (!file_exists($destination_file)) {
            copy($file, $destination_file);
        }
    }
}
add_action('after_switch_theme', 'copy_language_files_to_global_directory');

希望对您有所帮助!

评论

1赞 Benjamin 11/4/2023
这正是我想要的。非常感谢您抽出宝贵时间并编写了出色的代码。
0赞 Benjamin 11/9/2023
你好。我创建了一个关于您编写的相同代码的新问题。如果可能的话,看看这个问题:将文件放入路径后,立即复制