首页 > 解决方案 > wp_set_script_translations 不加载翻译文件

问题描述

我正在关注关于翻译自定义块的手册。这是我的语言文件夹在此处输入图像描述,然后在插件初始化函数中我尝试加载它。这是我的代码在此处输入图像描述,但是当我插入我的自定义块时它没有被翻译,所以 wordpress 不会加载翻译。我错过了什么?此致

附加信息:

这是块插件初始化功能,也许我在那里做错了什么?

function create_block_gutrs_slider_block_init() {

//register scripts
/**
 * https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/writing-your-first-block-type/#enqueuing-block-scripts
 */
// automatically load dependencies and version
$asset_file = include( plugin_dir_path( __FILE__ ) . 'build/index.asset.php');

wp_register_script(
    'gutrs-slider-front-script',
    plugins_url( 'build/gutrsfrontscript.js', __FILE__ ),
    ['wp-i18n'],
    $asset_file['version']
);

/**
 * translation
 * https://developer.wordpress.org/block-editor/how-to-guides/internationalization/
 */

if (function_exists('wp_set_script_translations')) {
    wp_set_script_translations( 'gutrs-slider-script', 'gutrs-slider', plugin_dir_path( __FILE__ ) . 'languages' );
}

register_block_type( __DIR__ ,array(
    'script' => 'gutrs-slider-front-script'
));
}
add_action( 'init', 'create_block_gutrs_slider_block_init' );

标签: wordpress-gutenberglanguage-translation

解决方案


在调用函数wp_set_script_translations之前,您需要使用wp-i18n依赖项注册加载脚本:

function my_enqueue_scripts()
{
  wp_enqueue_script( 'gutrs-slider-script', **YOUR_SCRIPT_URL**, ['wp-i18n'] );
  wp_set_script_translations( 'gutrs-slider-script', 'gutrs-slider', **LANGUAGES PATH**);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );

wp_set_script_translations需要在wp_enqueue_scripts操作中


推荐阅读