用于翻译Ajax加载内容的Transposh插件

时间:2014-11-15 00:12:04

标签: javascript wordpress translation

每次动态更新购物车时,我都试图让transposh plugin翻译。目前,插件将翻译,然后woocommerce将更新购物车,因此翻译将消失。

我在WooCommerce' checkout.js中找到了以下代码:

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

我相信这是代码(我只能找到它的缩小版本),以便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);

每次购物车更新时,我应该在checkout.js中添加什么才能触发翻译?

让我知道我应该提供的其他细节。

编辑:我应该注意到我被告知购物车正在通过AJAX进行更新。经过研究,transposh的插件创建者建议用户查看on_init function中的transposh.php

这是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"));
    }

以下是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');
                }
            }
        });

    }

1 个答案:

答案 0 :(得分:1)

经过一番挖掘,因为我不是php专家既不是wp专家,但我可以告诉问题在哪里。

首先,您应该了解add_action是什么,它得到了很好的解释here

如果你需要为&#34; add_foobar&#34;创建一个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
}

使用上面的例子,任何时候向WordPress发送一个AJAX请求,以及请求的动作&#39;属性设置为&#39; add_foobar&#39;,此挂钩将自动执行。例如,以下代码将执行上述钩子。

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

所以现在你得到了动作是如何工作的,那么你必须从transposh.php文件中获取transposh.php ajax部分的工作原理(我建议你在一个好的文本编辑器中打开文件,比如崇高的文本),在线437

//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;
        }

这简单地告诉我们的脚本在调用此动作时触发翻译,你需要做的就是稍微自定义这一行,以便激活你的ajax请求(update_checkout())。

如果您选中update_checkout()功能,则会找到相应的操作:'woocommerce_update_order_review'

<强>解决方案:

<强> 1。添加你的wp动作
    add_action(&#39; wp_woocommerce_update_order_review&#39;,&#39; woocommerce_update_order_review&#39;);     //最好将其添加到transposh.php中的第207行,并添加其他添加操作。

<强> 2。不要添加自己的函数,只需修改当前的buddypress示例。

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

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。这家伙建议在transposh.php

的第352行添加以下条件
if ($this->is_special_page($_SERVER['REQUEST_URI']))

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

在此处找到:http://cl.ly/Shdn/o

我希望我有一个链接到你正在使用它的页面,但是你无法提供一个例子,所以我希望这个解决方案能够正常运行。