Is it possible to create automatically a product after a user registers?
I\'m creating a sort of marketplace, so when a user signs up as vendor, I want Woocommerce t
You can achieve this by hooking it to
user_register
because WordPress core handles user registration and runs the user_register hook right after a user is registered. and to create a product you can use wp_insert_post methord to insert post withpost_type = product
Here is the code:
add_action( 'user_register', 'myCustomProduct', 10, 1 );
function myCustomProduct($user_id)
{
$user_info = get_userdata($user_id);
$display_name = $user_info->display_name;
$user_full_name = get_user_meta($user_id, 'first_name', TRUE) . ' ' . get_user_meta($user_id, 'last_name', TRUE);
$my_product_name = 'Booking - ' . trim($user_full_name);
$my_slug = 'calendar-' . str_replace(array(' '), '', strip_tags($display_name));
$post = array(
'post_author' => $user_id,
'post_content' => '',
'post_status' => "publish",
'post_title' => wp_strip_all_tags($my_product_name),
'post_name'=> $my_slug,
'post_parent' => '',
'post_type' => "product",
);
//Create Post
$post_id = wp_insert_post($post, $wp_error);
//set Product Category
//wp_set_object_terms( $post_id, 'Your Category Name ', 'product_cat' );
//set product type
wp_set_object_terms($post_id, 'simple', 'product_type');
update_post_meta($post_id, '_visibility', 'visible');
update_post_meta($post_id, '_stock_status', 'instock');
update_post_meta($post_id, 'total_sales', '0');
update_post_meta($post_id, '_sku', "");
update_post_meta($post_id, '_product_attributes', array());
update_post_meta($post_id, '_manage_stock', "no");
update_post_meta($post_id, '_backorders', "no");
update_post_meta($post_id, '_stock', "");
//update_post_meta($post_id, '_downloadable', 'yes');
//update_post_meta($post_id, '_virtual', 'yes');
//update_post_meta($post_id, '_regular_price', "1");
//update_post_meta($post_id, '_sale_price', "1");
//update_post_meta($post_id, '_purchase_note', "");
//update_post_meta($post_id, '_featured', "no");
//update_post_meta($post_id, '_weight', "");
//update_post_meta($post_id, '_length', "");
//update_post_meta($post_id, '_width', "");
//update_post_meta($post_id, '_height', "");
//update_post_meta($post_id, '_sale_price_dates_from', "");
//update_post_meta($post_id, '_sale_price_dates_to', "");
//update_post_meta($post_id, '_price', "1");
//update_post_meta($post_id, '_sold_individually', "");
}
Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.
The code is tested and fully functional.
Please Note: I have assumed that your registration form has first_name
and last_name
field otherwise if you are using default WooCommerce registration form then it only has email
and password
field, So then above code will generate a product name as Booking -
.
Hope this helps!