2016-11-24 102 views
4

我有一個WooCommerce商店,我試圖添加一個特定的產品到Woocommerce購物車的第一次購買者只。我已經有了以下的PHP代碼。添加一個項目到購物車的第一次購買

但由於某種原因,它不起作用。

這是我的代碼:

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

    } 
} 

我真的很感激,如果有人可以幫助我。

感謝

+0

你有什麼錯誤嗎?什麼不起作用? – Roman

回答

3

有2次失誤在你的代碼和其他一些東西:

  • 你在利用現有的woocommerce鉤來命名你的函數
  • 的post_type不'shop_prder''shop_order'

這裏是改變的代碼:

// 'woocommerce_add_to_cart' is an existing woocommerce hook so you can't use it to name your custom function here… 
add_action('woocommerce_before_cart','first_time_buyers'); 

function first_time_buyers(){ 
    if(!is_admin() && is_user_logged_in()){ 

     $product_id = 912; 
     $found = false; 
     $first_customer = true; 

     // Getting current customer valid orders (see 'post_status' below) 
     $customer_orders=get_posts(array(
      'meta_key' => '_customer_user', 
      'meta_value' => get_current_user_id(), 
      'post_type' => 'shop_order', // <= NOT 'shop_prder' but 'shop_order' 
      // We add the accepted orders status here 
      'post_status' => array('wc-on-hold', 'wc-processing', 'wc-completed'), 
      'numberposts' => -1 
     )); 

     if(count($customer_orders) > 0) 
      $first_customer = false; 

     if (!WC()->cart->is_empty()) 
      foreach (WC()->cart->get_cart() as $cart_item) 
       if ($product_id == $cart_item['product_id']) { 
        $found = true; 
        break; 
       } 

     if (!$found && $first_customer){ 
      WC()->cart->add_to_cart($product_id); 
     } 
    } 
} 

代碼放在您的活動子主題(或主題)的任何PHP文件或也是任何一個插件的PHP文件。

這是測試和功能齊全。

相關問題