簡體   English   中英

使用PolyLang更新購物車中的關鍵字(AJAX / WooCommerce)

[英]Using PolyLang to update keywords in shopping cart (AJAX/WooCommerce)

該線程的幫助下,我有了一個函數,該函數可以顯示和更新帶有AJAX的WooCommerce中購物車的金額和總價。 我沒有想到的問題是,我在網站上使用了PolyLang,因此當用戶更改頁面上的語言時,希望翻譯“ product”和“ products”的關鍵字。

我試圖在functions.php中的AJAX調用之前在條件中使用pll_current_language()掛鈎,然后根據當前語言定義變量$item$items並將這些關鍵字插入AJAX返回的字符串中。 我在模板文件中使用了類似的條件,所以它在那里工作。

但是,此功能無法正常工作。 這是我設置的方式:

的functions.php

function woocommerce_header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;

    ob_start();

    // Cart Translations
    $lang = pll_current_language();
    $item;
    $items;

    if ($lang == 'sv'){
    $item = "produkt";
    $items = "produkter";
    } else if ($lang == 'en') {
        $item = "product";
    $items = "products";
    }

    ?>
    <a class="cart-customlocation wpmenucart" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d ' . $item, '%d ' . $items, WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>
    <?php
    $fragments['a.cart-customlocation'] = ob_get_clean();
    return $fragments;
}

add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment', 30, 1 );

我遇到的問題是,即使我訪問了英語頁面, pll_current_language()掛鈎也始終返回“ sv”。 看來我無法在functions.php中使用該掛鈎,還是我錯過了一些東西? 您對如何進行這項工作有任何建議嗎?

我一直在尋找相同的解決方案。 然后,我才意識到$ lang = pll_current_language(); 無法正確提取Cookie。 因此,作為解決方法。 我開始為此使用$ _COOKIE。

function sn_get_cart_url() {
    $lang = $_COOKIE['pll_language'];
    $cart_page_id = get_option( 'woocommerce_cart_page_id' );

    if(function_exists('pll_get_post')) {
       $cart_page_id = pll_get_post($cart_page_id, $lang); 
    }
    return get_permalink($cart_page_id);
}

我對插件編碼沒有深入研究。 但這可能會解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM