I need to automatically add a product to the cart after user registration (which worked) but to decide which product to add by the user meta (which doesn't work).
The first action was just to add a product after registration and it worked perfectly:
add_action( 'user_register', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 115;
$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 );
}
}
}
Now I need to add a specific product according to lists I have of users promoID I got, but it doesn't add anything to the cart. example of the code:
add_action( 'user_register', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$group1iid1 = array("1", "2", "3", "4");
$group1iid2 = array("5", "6", "7", "8");
if (in_array("2", $group1iid1)) {
$product_id = 115;
WC()->cart->add_to_cart( $product_id );
} elseif (in_array("0", $group1iid2)) {
$product_id = 219;
WC()->cart->add_to_cart( $product_id );
} else {
$product_id = 231;
WC()->cart->add_to_cart( $product_id );
}
}
}
If I take the code to a template file and just echo something instead of adding a product - it works ok, but when it's like this in the function.php > nothing happens.
What am I missing?
There are missing things in your code:
In your first condition you need also to add
is_user_logged_in()
condition, as I suppose that this code is for new registrated users only.You need to get for the current user, HIS Promo ID value. I suppose that this value is set in user metadata, so to get this Promo ID value with
get_user_meta()
function, you have to define the correctmeta_key
.In your code you have to replace in your conditions
'2'
and'0'
values by the current user Promo ID…(Also
elseif (in_array("0", $group1iid2)) {
condition is going to be always false as"0"
value doesn't exist in$group1iid2
)As I can't test for real all this, Here is some kind of work around, based on your code (without any guaranty):