Skip to content

Instantly share code, notes, and snippets.

@justingreerbbi
Created January 23, 2018 16:43
Show Gist options
  • Select an option

  • Save justingreerbbi/a2c7c831c3d22a0ae7727f449917b6b9 to your computer and use it in GitHub Desktop.

Select an option

Save justingreerbbi/a2c7c831c3d22a0ae7727f449917b6b9 to your computer and use it in GitHub Desktop.
Create a product dynamically in WooCommerce
$pName = $params["name"];
$pDescription = 'Wallet Deposit';
$pPrice = $params["tc_price"];
$post_title = 'Fund Deposit ' . rand( 1000, 9999 ) . ' - ' . floatval( $params["tc_price"] ) . ' Credits';
$post = array(
'post_author' => $pName, // User ID
'post_content' => $pDescription,
'post_status' => "public",
'post_title' => $post_title,
'post_type' => "product",
);
// create product
$product_id = wp_insert_post( $post );
// type of product
wp_set_object_terms( $product_id, 'simple', 'product_type' );
// Required for the credit to process correctly
wp_set_object_terms( $product_id, array( 'credit', 'dynamic_uwcs' ), 'product_cat' );
//add price to the product, this is where you can add some descriptions such as sku's and measurements
update_post_meta( $product_id, '_regular_price', $pPrice );
update_post_meta( $product_id, '_sale_price', $pPrice );
update_post_meta( $product_id, '_price', $pPrice );
// Specific to the product. $1 is equal to 1 credit
update_post_meta( $product_id, '_visibility', 'visible' );
//$product = wc_get_product($product_id);
//print '<pre>';
//print_r($product);
//exit;
// Add the product to the cart
WC()->cart->add_to_cart( $product_id, 1 );
// Redirect to the checkout page.
$checkout_url = wc_get_checkout_url();
wp_safe_redirect( $checkout_url );
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment