I have a WooCommerce store, and I'm trying to add a specific product to the Woocommerce basket only for first-time buyers. I already have the following php code.
But for some reason this will not work.
This is my code:
add_action('woocommerce_before_cart','woocommerce_add_to_cart');
function woocommerce_add_to_cart(){
if(! is_admin()){
global $woocommerce;
$product_id=912;
$found=false;
$first_customer = false;
if(is_user_logged_in()){
$user_id=get_current_user_id();
$customer_orders=get_posts(array(
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_prder',
'numberposts' => -1
));
if(count($customer_orders) > 0) {
$first_customer=true;
wc_add_notice( sprintf( "first custommer check",error));
$statuses=array('wc-failed','wc-cancelled','wc-refunded');
foreach($customer_orders as $tmp_orders){
$order =wc_get_order($tmp_orders->ID);
if (! in_array($order->get_status(),$statuses)){
wc_add_notice( sprintf( "first custommer tmp check",error));
$first_customer=false;
}
}
}
if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {
wc_add_notice( sprintf( "items in cart check",error));
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id ){
wc_add_notice( sprintf( "produkt id check",error));
$found = true;
}
}
}
}
if (!$found && $first_customer){
wc_add_notice( sprintf( "found and custommer check",error));
WC()->cart->add_to_cart($product_id);
}
}
}
I would really appreciate it if anyone could help me.
thank
source
share