简体   繁体   English

Transposh插件翻译Ajax加载的内容

[英]Transposh plugin to translate Ajax loaded content

I'm trying to get the transposh plugin to translate everytime the cart is updated dynamically. 我正在尝试使transposh plugin在每次购物车动态更新时进行翻译。 Currently, the plugin will translate and then woocommerce would update the cart thus the translations disappear. 当前,该插件将翻译,然后woocommerce将更新购物车,因此翻译消失。

I found the following code in WooCommerce's checkout.js : 我在WooCommerce的checkout.js找到了以下代码:

    // Event for updating the checkout
    $('body').bind('update_checkout', function() {
        clearTimeout(updateTimer);
        update_checkout();
});

I believe this is the code (I can only find the minified version of it) for how transposh gets the translations going in transposh.js : 我相信这是代码(我只能找到它的缩小的版本)通过Transposh如何得到翻译中去transposh.js

(function(c){function D(b,a){if(0!==c.trim(a).length){var d=function(){var b=c(this).attr("id").substr(c(this).attr("id").lastIndexOf("_")+1),a=c("#"+e+"img_"+b);c("#"+e+b).attr("data-source",1);a.removeClass("tr-icon-yellow").removeClass("tr-icon-green").addClass("tr-icon-yellow")};c("*[data-token='"+b+"'][data-hidden!='y']").html(a).each(d);c("*[data-token='"+b+"'][data-hidden='y']").attr("data-trans",a).each(d)}}function E(b,a){clearTimeout(v);h.push(b);r.push(a);D(b,a);v=setTimeout(function(){var b=
{ln0:t_jp.lang,sr0:s,action:"tp_translation",items:h.length},a;for(a=0;a<h.length;a+=1)b["tk"+a]=h[a],b["tr"+a]=r[a],t+=c("*[data-token='"+h[a]+"']").size();c.ajax({type:"POST",url:t_jp.ajaxurl,data:b,success:function(){var b=t/k*100;t_jp.progress&&c("#"+m).progressbar("value",b)}});r=[];h=[]},200)}function l(b,a){E(b,c("<div>"+c.trim(a)+"</div>").text());var d=(k-c("."+e+'[data-source=""]').size())/k*100;t_jp.progress&&c("#"+n).progressbar("value",d)}function w(b,a,d){c.ajax({url:t_jp.ajaxurl,dataType:"json",
type:"GET",data:{action:"tp_gp",tl:d,q:b},success:a})}function x(b,a){w(a,function(a){c(a.results).each(function(a){l(b[a],this)})},t_jp.lang)}function y(b,a,d){c.ajax({url:"https://www.googleapis.com/language/translate/v2",dataType:"jsonp",data:{key:t_jp.google_key,q:b,target:d,source:t_jp.olang},traditional:!0,success:a})}function F(b,a){y(a,function(d){"undefined"!==typeof d.error?x(b,a):c(d.data.translations).each(function(a){l(b[a],this.translatedText)})},t_jp.lang)}function p(b,a,d){if(t_jp.msn_key){var f=
"[";c(b).each(function(a){f+='"'+encodeURIComponent(b[a].replace(/[\\"]/g,"\\$&").replace(/(\r\n|\n|\r)/gm," "))+'",'});f=f.slice(0,-1)+"]";c.ajax({url:"//api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?appId="+t_jp.msn_key+"&to="+d+"&texts="+f,dataType:"jsonp",jsonp:"oncomplete",success:a})}else 1===z?setTimeout(function(){p(b,a,d)},500):(z=1,c.getScript("//www.microsofttranslator.com/ajax/v2/toolkit.ashx?loc=en&toolbar=none",function(){t_jp.msn_key=_mstConfig.appId;p(b,a,d)}))}function G(b,
a){s=2;p(a,function(a){c(a).each(function(a){l(b[a],this.TranslatedText)})},t_jp.binglang)}function A(b,a,d){c.ajax({url:"http://api.apertium.org/json/translate",data:{q:b,langpair:t_jp.olang+"|"+d,markUnknown:"no"},dataType:"jsonp",traditional:!0,success:a})}function H(b,a){s=3;A(a,function(a){200<=a.responseStatus&&300>a.responseStatus&&(void 0!==a.responseData.translatedText?l(b[0],a.responseData.translatedText):c(a.responseData).each(function(a){200===this.responseStatus&&l(b[a],this.responseData.translatedText)}))},
t_jp.lang)}function B(b,a){!t_jp.msn||"2"!==t_jp.preferred&&void 0!==t_jp.google?!t_jp.apertium||"en"!==t_jp.olang&&"es"!==t_jp.olang?t_jp.google_key?F(b,a):x(b,a):H(b,a):G(b,a)}function u(){var b=[],a=0,d=[],f=[];c("."+e+'[data-source=""]').each(function(){var e=c(this).attr("data-token"),g=c(this).attr("data-orig");void 0===g&&(g=c(this).html());1!==b[g]&&(b[g]=1,a+encodeURIComponent(g).length>I&&(B(f,d),a=0,d=[],f=[]),a+=encodeURIComponent(g).length,f.push(e),d.push(g))});B(f,d)}function C(b){"function"===
typeof c.xLazyLoader?b():(t_jp.$=c,c.getScript(t_jp.plugin_url+"/js/lazy.js",b))}function q(b){q.hit?b():(q.hit=!0,C(function(){c.fn.propAttr=c.fn.prop||c.fn.attr;c.xLazyLoader({js:t_jp.jQueryUI+"jquery-ui.min.js",css:t_jp.jQueryUI+"themes/"+t_jp.theme+"/jquery-ui.css",success:b})}))}var I=1024,k,e=t_jp.prefix,n=e+"pbar",m=n+"_s",s=1,t=0,v,h=[],r=[],z=0;t_jp.dgpt=w;t_jp.dgt=y;t_jp.dmt=p;t_jp.dat=A;t_jp.tfl=C;t_jp.tfju=q;t_jp.at=u;c(function(){t_jp.msn&&(t_jp.binglang=t_jp.lang,"zh"===t_jp.binglang?
t_jp.binglang="zh-chs":"zh-tw"===t_jp.binglang?t_jp.binglang="zh-cht":"mw"===t_jp.binglang&&(t_jp.binglang="mww"));c("."+e+"setdeflang").click(function(){c.ajax({url:t_jp.ajaxurl,data:{action:"tp_cookie"},cache:!1});c("."+e+"setdeflang").hide("slow");return!1});k=c("."+e+'[data-source=""]').size();c.ajaxSetup({cache:!0});k&&!t_jp.noauto&&(t_jp.google||t_jp.msn||t_jp.apertium)&&(t_jp.progress?q(function(){c("#"+e+"credit").css({overflow:"auto"}).append('<div style="float: left;width: 90%;height: 10px" id="'+
n+'"/><div style="margin-bottom:10px;float:left;width: 90%;height: 10px" id="'+m+'"/>');c("#"+n).progressbar({value:0});c("#"+m).progressbar({value:0});c("#"+m+" > div").css({background:"#28F828",border:"#08A908 1px solid"});u()}):u());t_jp.edit&&c.getScript(t_jp.plugin_url+"/js/transposhedit.js")})})(jQuery);

What should I add in the checkout.js to fire the translations everytime the cart is updated? 每当购物车更新时,我应该在checkout.js中添加什么来触发翻译?

Let me know what other details I should provide. 让我知道我还应该提供什么其他详细信息。

EDIT: I should note that I was told that the cart is being updated via AJAX. 编辑:我应该注意,我被告知购物车正在通过AJAX更新。 Upon research, the plugin creator of transposh had suggested users to look at the on_init function in transposh.php 经过研究,transposh的插件创建者建议用户查看transposh.phpon_init function

This is the on_init function : 这是on_init function

    /**
     * Setup a buffer that will contain the contents of the html page.
     * Once processing is completed the buffer will go into the translation process.
     */
    function on_init() {
    tp_logger('init ' . $_SERVER['REQUEST_URI'], 4);

    // the wp_rewrite is not available earlier so we can only set the enable_permalinks here
    if (is_object($GLOBALS['wp_rewrite'])) {
    if ($GLOBALS['wp_rewrite']->using_permalinks() && $this->options->enable_permalinks) {
    tp_logger("enabling permalinks");
    $this->enable_permalinks_rewrite = TRUE;
    }
    }

    // this is an ajax special case, currently crafted and tested on buddy press, lets hope this won't make hell break loose.
    // it basically sets language based on referred when accessing wp-load.php (which is the way bp does ajax)
    tp_logger(substr($_SERVER['SCRIPT_FILENAME'], -11), 5);
    if (substr($_SERVER['SCRIPT_FILENAME'], -11) == 'wp-load.php') {
    $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
    $this->attempt_json = true;
    }

    //buddypress old activity
    if (@$_POST['action'] == 'activity_get_older_updates') {
    $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
    $this->attempt_json = true;
    }

    tp_logger($_SERVER['REQUEST_URI'], 5);
    if (strpos($_SERVER['REQUEST_URI'], '/wpv-ajax-pagination/') === true) {
    tp_logger('wpv pagination', 5);
    $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
    }

    // load translation files for transposh
    load_plugin_textdomain(TRANSPOSH_TEXT_DOMAIN, false, dirname(plugin_basename(__FILE__)) . '/langs');

    //set the callback for translating the page when it's done
    ob_start(array(&$this, "process_page"));
    }

Here is the function for update_checkout() 这是update_checkout()的函数

function update_checkout() {

        if (xhr) xhr.abort();

        if ( $('select#shipping_method').size() > 0 || $('input#shipping_method').size() > 0 )
            var method = $('#shipping_method').val();
        else
            var method = $('input[name=shipping_method]:checked').val();

        var payment_method  = $('#order_review input[name=payment_method]:checked').val();
        var country         = $('#billing_country').val();
        var state           = $('#billing_state').val();
        var postcode        = $('input#billing_postcode').val();
        var city            = $('input#billing_city').val();
        var address         = $('input#billing_address_1').val();
        var address_2       = $('input#billing_address_2').val();

        if ( $('#shiptobilling input').is(':checked') || $('#shiptobilling input').size() == 0 ) {
            var s_country   = country;
            var s_state     = state;
            var s_postcode  = postcode;
            var s_city      = city;
            var s_address   = address;
            var s_address_2 = address_2;
        } else {
            var s_country   = $('#shipping_country').val();
            var s_state     = $('#shipping_state').val();
            var s_postcode  = $('input#shipping_postcode').val();
            var s_city      = $('input#shipping_city').val();
            var s_address   = $('input#shipping_address_1').val();
            var s_address_2 = $('input#shipping_address_2').val();
        }

        $('#order_methods, #order_review').block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url + ') no-repeat center', backgroundSize: '16px 16px', opacity: 0.6}});

        var data = {
            action:             'woocommerce_update_order_review',
            security:           woocommerce_params.update_order_review_nonce,
            shipping_method:    method,
            payment_method:     payment_method,
            country:            country,
            state:              state,
            postcode:           postcode,
            city:               city,
            address:            address,
            address_2:          address_2,
            s_country:          s_country,
            s_state:            s_state,
            s_postcode:         s_postcode,
            s_city:             s_city,
            s_address:          s_address,
            s_address_2:        s_address_2,
            post_data:          $('form.checkout').serialize()
        };

        xhr = $.ajax({
            type:       'POST',
            url:        woocommerce_params.ajax_url,
            data:       data,
            success:    function( response ) {
                if ( response ) {
                    var order_output = $(response);
                    $('#order_review').html(order_output.html());
                    $('body').trigger('updated_checkout');
                }
            }
        });

    }

After a bit of digging , and because im not php expert neither wp expert , but i can tell where the issue is. 经过一番挖掘,并且因为我不是php expert还是wp expert,但是我可以知道问题出在哪里。

First of all you should understand what add_action is , it is well explained here 首先,您应该了解什么是add_action ,这在这里有很好的解释

If you needed to create an AJAX handler for an "add_foobar" request, you would create a hook like this: 如果您需要为“ add_foobar”请求创建AJAX处理程序,则可以创建如下所示的钩子:

add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );

function prefix_ajax_add_foobar() {
    // Handle request then generate response using WP_Ajax_Response
}

Using the above example, any time an AJAX request is sent to WordPress, and the request's 'action' property is set to 'add_foobar', this hook will be automatically executed. 使用上面的示例,每当AJAX请求发送到WordPress,并且该请求的'action'属性设置为'add_foobar'时,该挂钩都会自动执行。 For example, the following code would execute the above hook. 例如,以下代码将执行上述钩子。

jQuery.post(
    ajaxurl, 
    {
        'action': 'add_foobar',
        'data':   'foobarid'
    }, 
    function(response){
        alert('The server responded: ' + response);
    }
); 

so now you got how actions works , then you have to get how the transposh.php ajax part works , from the transposh.php file ( i recommend you open the file in a good text editor like sublime text ) , in line 437 : 因此,现在您了解了动作的工作原理,然后必须从transposh.php文件中获取transposh.php ajax部分的工作原理(我建议您在第437行中使用诸如sublime text之类的优质文本编辑器打开该文件):

//buddypress old activity
        if (@$_POST['action'] == 'activity_get_older_updates') {
            $this->target_language = transposh_utils::get_language_from_url($_SERVER['HTTP_REFERER'], $this->home_url);
            $this->attempt_json = true;
        }

this simply tells our script to fire translation when this action is called, what you have to do is customizing this line a bit so it fires upon you ajax request (update_checkout() ). 这只是告诉我们的脚本在调用此动作时触发翻译,您需要做的是自定义此行,以便在您的ajax请求(update_checkout() )上触发。

if you check update_checkout() function you will find the corresponding action : 'woocommerce_update_order_review' 如果您检查update_checkout()函数,您将找到相应的操作: 'woocommerce_update_order_review'

Solution: 解:

1. Add you wp actions 1.添加您的wp操作
add_action( 'wp_woocommerce_update_order_review', 'woocommerce_update_order_review' ); add_action('wp_woocommerce_update_order_review','woocommerce_update_order_review'); //preferably add this to line 207 in transposh.php with other add actions. //最好使用其他添加操作将其添加到transposh.php中的207行。

2. Instead of adding your own function , just modify the current buddypress example. 2.无需添加您自己的功能,只需修改当前的buddypress示例。

if (@$_POST['action'] == 'activity_get_older_updates')

to be 成为

if (@$_POST['action'] == 'activity_get_older_updates' || @$_POST['action'] == 'woocommerce_update_order_review' )
//fire translation if action is equal to buddypress activity get older updates or action is equal to woocommerce update checkout.

3. this guy recommends adding following condition to line 352 in transposh.php 3.这个人建议在transposh.php的352行中添加以下条件

if ($this->is_special_page($_SERVER['REQUEST_URI']))

to be 成为

if ($this->is_special_page($_SERVER['REQUEST_URI'])&& !$this->attempt_json)

found here : http://cl.ly/Shdn/o 在这里找到: http : //cl.ly/Shdn/o

I hope i had a link to your page where you are using this , but you could not provide an example , so i hope this solution will work as it was meant to be. 我希望我有一个指向您正在使用此页面的页面的链接,但是您无法提供示例,所以希望此解决方案能够按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM