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:

require_once("wp-blog-header.php");
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]
    print_r(WC());

    print_r(WC()->cart);

    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?

0

Leave a Reply

Your email address will not be published. Required fields are marked *