简而言之,以下是在我的案例中有效的解决方案:
<?php
function my_theme_ajax_load_more_products() {
// Using the load_textdomain() function to make sure that
// the translation file used in the template below is loaded.
// This is the line that solves the issue, more on it bellow.
load_textdomain(\'woocommerce\', WP_CONTENT_DIR . \'/languages/plugins/woocommerce-\' . get_locale() . \'.mo\');
// Some code not related to the issue to give some plain context.
$args = json_decode(stripslashes($_POST[\'query_vars\']), true);
$args[\'offset\'] = $_POST[\'offset\'];
$query =new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
// This is standart template part.
// It contains plenty gettext calls pointed to
// WooCommerce\'s text domain.
// The gettext calls were ending untranslated before I
// added the load_textdomain().
wc_get_template_part(\'content\', \'product\');
endwhile;
endif;
wp_reset_postdata();
die;
}
add_action(\'wp_ajax_load_more_products\', \'my_theme_ajax_load_more_products\');
add_action(\'wp_ajax_nopriv_load_more_products\', \'my_theme_ajax_load_more_products\');
我用了
get_locale()
在代码中的多个位置(甚至在AJAX操作中)执行函数,以确保获得正确的语言环境。获得正确的代码使我认为未翻译文本的问题与
text domain. 我已经将主题的文本域添加为
described in WP\'s docs 我将一些测试文本翻译成保加利亚语(因此我生成了bg\\u bg.mo),但AJAX操作中的gettext函数没有翻译测试文本。
经过更多的研究,我发现一个人可以添加一个。mo文件load_textdomain()
而不是使用load_theme_textdomain()
. 因为我需要WooCommerce文本域中的所有翻译load_textdomain()
指向WooCommerce的。mo文件。WooCommerce\'s docs 说文件在wp-content/languages/.
// For translations of plugins as WooCommerce
load_textdomain(\'woocommerce\', WP_CONTENT_DIR . \'/languages/plugins/woocommerce-\' . get_locale() . \'.mo\');
// WP_CONTENT_DIR gets the directory path of the wp-content folder
// get_locale() returns the current language code of the page
// For translations of your theme
load_textdomain(\'woocommerce\', get_template_directory() . \'/languages/\' . get_locale() . \'.mo\');
Load text domain\'s docs.