簡體   English   中英

Woocommerce將可定制產品添加到購物車

[英]Woocommerce Add Customizable Product to Cart

我正在嘗試向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 );}

我完全離開了嗎? 或者我該怎么做?

是的,您可以使用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 
);

這對我有用-插入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' )  );

    }

  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM