【问题标题】:Determine language in functions.php [wpml]在functions.php中确定语言[wpml]
【发布时间】:2017-06-08 13:51:08
【问题描述】:

我在functions.php中有一个函数,它会在访问网站时自动将woocommerce产品按ID添加到购物车中。

网站是双语的,功能无法确定翻译后的产品ID。

所以,我想知道是否可以在functions.php中添加wpml函数,它确定前端的第一种语言,然后执行函数,如下所示:

<?php if(wpml_getLanguage()=='en'); ?>
---do function for product 22---
<?php elseif(wpml_getLanguage()=='it'); ?>
---do function for product 45--
<?php endif; ?>

我的代码:

add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
    if ( ! is_admin() ) {
        $product_id = 22;
        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->id == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }
}

【问题讨论】:

标签: php wordpress woocommerce wpml


【解决方案1】:

您可以使用原生 WPML 变量 ICL_LANGUAGE_CODE 轻松获得此信息。

您可以在以下页面找到有关此主题的更多信息: https://wpml.org/documentation/support/wpml-coding-api/

【讨论】:

  • 我已经完成了,但对于将来会看到这个话题的人来说,这并不是完整的答案。感谢您的关注。
【解决方案2】:

这可以放到functions.php中

add_action( 'init', 'add_product_on_language' );

function add_product_on_language(){
    if ( ! is_admin() ) {

        if( ICL_LANGUAGE_CODE == 'en' ){
            $product_id = 22;
        } elseif ( ICL_LANGUAGE_CODE == 'it' ) {
            $product_id = 45;
        }

        $found = false;
        //check if product already in cart
        if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
            foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
                $_product = $values['data'];
                if ( $_product->id == $product_id )
                    $found = true;
            }
            // if product not found, add it
            if ( ! $found )
                WC()->cart->add_to_cart( $product_id );
        } else {
            // if no products in cart, add it
            WC()->cart->add_to_cart( $product_id );
        }
    }    
}

【讨论】:

  • @Nick_n1 我调整了代码,使它可以放到functions.php中
猜你喜欢
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 2018-01-14
相关资源
最近更新 更多