2017-09-14 68 views
0

隨着每張照片上傳,我創建一個woocommerce產品,你可能會認爲在某些時候我會有很多未使用的產品。我將產品ID和圖片上傳鏈接保存到文本文件。如何在沒有操作的情況下獲取woocommerce購物車內容?

我想要做的是在24小時後刪除產品,如果它不在購物車中,我想用cron做到這一點。

我有的問題是我不明白如何使全球woocommerce屬性也可用於計劃事件(克朗)。

這是我的設置安排的事件:

add_action('daily_product_removal', 'delete_unused_products'); 

function activate() { 
    wp_schedule_event(time(), 'daily', 'daily_product_removal'); 
} 

function deactivate() { 
    wp_clear_scheduled_hook('daily_product_removal'); 
} 

佑在購物車功能:

function woo_in_cart($product_id) { 
    global $woocommerce; 

    foreach($woocommerce->cart->get_cart() as $key => $val) { 
     $_product = $val['data']; 

     if($product_id == $_product->id) { 


     return true; 
     } 
    } 

    return false; 
} 

主要功能:

function delete_unused_products() { 

    $woocommerce = new Client(
     'site_link', 
     'ck_numbers', 
     'cs_numbers', 
     [ 
      'wp_api' => true, 
      'version' => 'wc/v1', 
     ] 
    ); 

    $myFile = "products.txt"; 

    $myFileLink = fopen($myFile, 'r'); 

    $products = []; 

    while(!feof($myFileLink)) { 
      $this_line = fgets($myFileLink); 
      array_push($products,$this_line); 
    } 

    fclose($myFileLink); 

    foreach($products as $i => $item) { 

     $product = unserialize($item); 
     $creation_date_from_file = $product->creation_date; 
     $product_id = $product->product_id; 

     $createDate = strtotime($creation_date_from_file); 

     if (strtotime("$creation_date_from_file +1 day") <= time() && !woo_in_cart($product_id)) { // created more than 24 hours ago and is not added in cart 

      $results = $woocommerce->delete('products/' . $product_id, ['force' => true]); 

      if (file_exists($item->local_url)) { 
       unlink($item->local_url); 
      } 
     if (file_exists($item->local_mockup_url)) { 
      unlink($item->local_url); 
     } 

     file_put_contents($myFile, str_replace($i . "\r\n", "", file_get_contents($myFile))); // delete the line 

    } 
} 

}

這個問題我有,如果我跑下woocommerce具體行動掛鉤這一功能,可以說:

add_action('woocommerce_cart_contents', 'delete_unused_products'); 

它的罰款,但如果我運行這個,因爲我想(通過的cron)我得到的錯誤,像$ woocommerce->車沒有定義。

無法包裹我的頭如何使這項工作。 謝謝。

回答

0

您的設計存在嚴重缺陷。購物車是會話的一部分。買方正在查看前端頁面時存在活動會話。但是,當cron作業運行時,沒有買方查看前端頁面,因此沒有活動會話,因此沒有購物車。

相關問題