2

I have function in functions.php , which automatically adds woocommerce product by ID to cart when website is visited.

The website is bilingual and the function can't determine translated product ID.

So, I want to know if is possible to add wpml function in functions.php, which determines first language of front end, then executes function, something like this:

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

My code:

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 );
        }
    }
}
Nick_n1
  • 51
  • 4
  • [Adding a code to WordPress header based on local language into functions.php - WPML](https://stackoverflow.com/questions/43788386/adding-a-code-to-wordpress-header-based-on-local-language-into-functions-php) – LoicTheAztec Jun 03 '17 at 18:06

2 Answers2

2

You can easily get this by using the native WPML variable ICL_LANGUAGE_CODE.

You can find more information about this topic on the following page: https://wpml.org/documentation/support/wpml-coding-api/

mujuonly
  • 11,370
  • 5
  • 45
  • 75
  • I've already done, but it is not full answer for person who will see this topic in future. Thanks for yor attention. – Nick_n1 Jun 07 '17 at 04:12
0

This can be dropped into 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 );
        }
    }    
}
Aleksandar
  • 1,496
  • 1
  • 18
  • 35