首页 文章

Woocommerce将可定制产品添加到购物车

提问于
浏览
1

我正在尝试为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 );}

我完全没了?或者我该怎么做?

2 回答

  • 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

    这对我有用 - 插入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' )  );
    
        }
    
      }
    
    }
    

相关问题