我在functions.php中有功能,当访问网站时,它会自动将ID的woocommerce产品添加到购物车。
网站是双语的,功能无法确定已翻译的产品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 );
}
}
}
答案 0 :(得分:2)
您可以使用原生WPML变量ICL_LANGUAGE_CODE
轻松获得此功能。
您可以在以下页面找到有关此主题的更多信息: https://wpml.org/documentation/support/wpml-coding-api/
答案 1 :(得分:0)
这可以放入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 );
}
}
}