Nick_n1
Nick_n1

Reputation: 51

Determine language in functions.php [wpml]

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

Upvotes: 2

Views: 2890

Answers (2)

Aleksandar
Aleksandar

Reputation: 1766

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

Upvotes: 0

mujuonly
mujuonly

Reputation: 11861

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/

Upvotes: 2

Related Questions