I'm writing a custom integration plugin for Woocommerce, to add a dynamic product to the cart. Right now, without the plugin, I make POST request via a form inside an external page containing the product data to a simple php file:

header("HTTP/1.1 200 OK");
global $woocommerce;

//omitting id, quantity, var and attribute definition

$ret = WC()->cart->add_to_cart($id,$quantity, $var, $arr);

This works as expected, and the product is successfully added. Now, I'm moving the logic inside a native plugin, this is the code run after a submission to <form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="POST">:

function custom_go_to_preview(){ 
    //[omitting id, quantity, etc]


    WC()->cart->add_to_cart($id,$quantity, $var, $arr);

add_action( 'admin_post_nopriv_custom_go_to_preview', 'custom_go_to_preview');
add_action( 'admin_post_custom_go_to_preview', 'custom_go_to_preview' );

The output of the print_r is:

WooCommerce Object ( [version] => 2.6.14 [session] => [query] => WC_Query Object ( [query_vars] => Array ( [order-pay] => order-pay [order-received] => order-received [orders] => orders [view-order] => view-order [downloads] => downloads [edit-account] => edit-account [edit-address] => edit-address [payment-methods] => payment-methods [lost-password] => lost-password [customer-logout] => customer-logout [add-payment-method] => add-payment-method [delete-payment-method] => delete-payment-method [set-default-payment-method] => set-default-payment-method ) ) [product_factory] => WC_Product_Factory Object ( ) [countries] => WC_Countries Object ( [locale] => [address_formats] => ) [integrations] => WC_Integrations Object ( [integrations] => Array ( ) ) [cart] => [customer] => [order_factory] => WC_Order_Factory Object ( ) [api] => WC_API Object ( [server] => [authentication] => ) ) 
Fatal error: Call to a member function add_to_cart() on a non-object in [...]/wp-content/plugins/my_plugin/my_plugin.php on line 53

long story short, the cart is null, even if it is not empty if I go to mywebsite.com/cart or any other page. How can I solve this? Is there a kind of sessions conflict?

  • Did you solve this? – tobros91 May 3 '17 at 12:12
  • Nope, I solved by doing an ajax submit and hooking the add_to_cart function on the ajax admin hook. – Fabrizio Mele May 3 '17 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.