[英]Woocommerce Add Customizable Product to Cart
I'm trying to add a customizable product to the woocommerce cart. 我正在尝试向woocommerce购物车添加可自定义的产品。
I have all details calculated and ready to be able to add it to the cart. 我已经计算了所有详细信息,并准备将其添加到购物车中。
Looking into the woocommerce api, it looks like I can use REST, but I'm just thinking there must be an easier way with regular php. 研究woocommerce api,看起来我可以使用REST,但是我认为常规php必须有一种更简单的方法。
I'm thinking something like this: 我在想这样的事情:
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 );}
Am I totally off ? 我完全离开了吗? or how can I do this ? 或者我该怎么做?
Yes, you can use the add_to_cart()
method available on the WC_Cart
object. 是的,您可以使用WC_Cart
对象上可用的add_to_cart()
方法。 Your example is mostly correct, however you would need to provide the numeric $product_id
and $variation_id
. 您的示例大部分是正确的,但是您需要提供数字$product_id
和$variation_id
。
It is also preferable to access the WooCommerce object using WC()
rather than the global $woocommerce
. 也最好使用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
);
This worked for me - inserted in functions.php and the reference to this function via a html form: 这对我有用-插入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.