2015-06-16 223 views
1

我正在嘗試向woocommerce購物車添加可定製產品。Woocommerce將可定製產品添加到購物車

我已計算好所有細節並準備好將其添加到購物車。

縱觀woocommerce api,它看起來像我可以使用REST,但我只是認爲必須有一個更簡單的方法與常規的PHP。

我想是這樣的:

function add_product_to_wc(){ 
             global $woocommerce; 

             $product_id = $name; 
             $variationid = $type; 
             $spec = array(); 
             $spec['Dimension'] = $dimension; //user select Dimension 
             $spec['ColorOne'] = $colorOne; //user select color 1 
             $spec['ColorTwo'] = $colorTwo; //user select color 2 

             $woocommerce->cart->add_to_cart($product_id, $variationid, $spec, null);} 

我完全關閉?或者我該怎麼做?

回答

0

這爲我工作 - 插入的functions.php,並通過HTML表單的參考這個函數:

add_action('wp_loaded', 'customcart'); 


function customcart() { 

    if (isset($_POST["addcustomcarts"])) { 

    global $woocommerce; 

    $my_post = array(
     'post_title' => $_POST["textInput"], 
     'post_content' => 'This is my post.', 
     'post_status' => 'publish', 
     'post_author' => 1, 
     'post_type'  =>'product' 
    ); 

    // Insert the post into the database 
    $product_ID = wp_insert_post($my_post); 

    if ($product_ID){ 
     wp_set_object_terms($product_ID, 'design-selv-skilte', 'product_cat'); 
     add_post_meta($product_ID, '_regular_price', 100); 
     add_post_meta($product_ID, '_price', 100); 
     add_post_meta($product_ID, '_stock_status', 'instock'); 
     add_post_meta($product_ID, '_sku', 'designselvskilt');  
     add_post_meta($product_ID, '_visibility', 'hidden'); 
     //wp_set_object_terms($product_ID, 'tekst på mit skilt', text1, False); 

     $woocommerce->cart->add_to_cart($product_ID, $quantity=1); 

     exit(wp_redirect('/kurv') ); 

    } 

    } 

} 
0

是的,您可以使用WC_Cart對象上的add_to_cart()方法。你的例子大多是正確的,但是你需要提供數字$product_id$variation_id

最好使用WC()而不是global $woocommerce訪問WooCommerce對象。

$product_id = 123; // use the real product ID 
$variation_id = 456; // use the real variation ID 
$dimension = 'Large'; 
$colorOne = 'Color One'; 
$colorTwo = 'Color Two'; 

WC()->cart->add_to_cart( 
    $product_id, 
    $variation_id, 
    array('Dimension'=>$dimension, 'ColorOne'=>$colorOne, 'ColorTwo'=>$colorTwo), 
    null 
); 
+0

但如果該產品是通過定製創建定製的產品 - 如此事先沒有產品ID。我應該在同一個實例中創建產品嗎? –

+0

總是有一個產品ID,你必須首先在WooCommerce中創建變量產品。您也可以通過編程的方式來完成,但仍然需要先創建,以便您可以使用該ID將其添加到您的購物車。 – doublesharp

相關問題