I’m not sure exactly what you are doing, but the following code did work for me in that it created a new product and added it to the cart. Note, I had to use $_GET
to test on my setup since I don’t have the rest of your code and didn’t feel like creating a form.
EDIT: I’ve added a simple <form>
element and switched to $_POST
.
EDIT 2: I’ve removed the form. Apparently the OP has the form on the front page.
add_action('init', 'customcart');
function customcart() {
if (isset($_POST["addcustomcarts"])) {
global $woocommerce;
$my_post = array(
'post_title' => 'My post',
'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 ){
add_post_meta($product_ID, '_regular_price', 100 );
add_post_meta($product_ID, '_price', 100 );
add_post_meta($product_ID, '_stock_status', 'instock' );
//Getting error on this line.
$woocommerce->cart->add_to_cart( $product_ID, $quantity=1 );
exit( wp_redirect( get_permalink( woocommerce_get_page_id( 'cart' ) ) ) );
}
}
}