I've created a plugin that requires on-the-fly WooCommerce product creation (Simple Product) and adding to the visitor's cart. All of this happens on the front end / public side - i.e. visitor fills in a form on a page and submit it. I've used resources such as this answer to get started. Once the product is successfully created, I use:

$product_id = $this->create_product($product);
// Error checking, etc
$result = WC()->cart->add_to_cart($product_id);

To add it to the cart. This works well while I'm logged in (on the admin side - front-end / public side probably picks up that I'm logged in).

But when I'm not logged in: Only the product creation seems to work as I can see the product in the db but the visitor's cart is empty. And the $result seems fine.

$result = 44f683a84163b3523afe57c2e008bc8c

I've change the setting of WooCommerce but it made no difference. enter image description here


For clarity: I don't want to force a visitor to register before adding the product to the cart.

Side effect: I get no products in my cart when I'm not logged in but when I log in and add another product then I get both in my cart.

How do I ensure that a product created like this gets added to the visitors cart?

  • please check this if(is_user_logged_in() ){ Nov 28, 2018 at 12:56
  • @vikrantzilpe I will check it, but what do I do if if(is_user_logged_in()) is false?
    – TungstenX
    Nov 28, 2018 at 13:08
  • hi add some code please check .i hope this code solve your problem. Nov 29, 2018 at 7:16
  • @vikrantzilpe If there is no other way then I'll automatically register a user. But it will not be a good UX for the visitor
    – TungstenX
    Nov 30, 2018 at 6:01
  • @TungstenX, I believe you've seen my (deleted) answer? ;) It (the code) actually does work and the answer is also valid... but as Greg pointed out in his answer, you might better the product to the cart via the wp_loaded action or other action which fires before any output is sent to the browser.
    – Sally CJ
    Dec 7, 2018 at 1:53

1 Answer 1


I did two tests on my dev site

add_action( "wp_loaded", function() {


add_action( "wp_footer", function() {

Both var_dump a hash, but only the first one actually adds a product to the cart, the second prints the hash but does not add anything.

What is happening is that in the second test some content is already sent to browser and WooCommerce is unable to set a cart cookie.

If you will make sure you are running the add_to_cart() method before content is sent to the browser (for example run it in wp_loaded action) then your code should work fine.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.