Here is what I am trying to do: A fellow site makes a request to my site like this:
https://example.com/?add-to-cart=14&REQ&id=32&key=6337
Then if the REQ
parameter exists, I crosscheck with a separate database to see the price in a table row where theID
and KEY
match. Then I use this price to add the custom product to cart.
And here is the code as a separate plugin after seeing this solution:
add_filter( 'woocommerce_add_cart_item' , 'set_woo_prices');
add_filter( 'woocommerce_get_cart_item_from_session', 'set_session_prices', 20 , 3 );
function set_woo_prices( $woo_data ) {
$w_price = 999.99;
if (isset($_GET['REQ'])) {
$w_id = $_GET['id'];
$w_key = $_GET['key'];
//we ask the database
$my_wpdb = new WPDB( 'rt', 'rt', 'db', 'localhost');
$curr_req = $my_wpdb->get_row( "SELECT * FROM tbl WHERE id = $w_id", ARRAY_A );
if ( $curr_req['keypin'] == $w_key ){
$w_price = $curr_req['price'];
}
else {
exit;
}
$woo_data['data']->set_price( $w_price );
$woo_data['my_price'] = $w_price;
return $woo_data;
}
};
function set_session_prices ( $woo_data , $values , $key ) {
if ( ! isset( $woo_data['my_price'] ) || empty ( $woo_data['my_price'] ) ) { return $woo_data; }
$woo_data['data']->set_price( $woo_data['my_price'] );
return $woo_data;
};
But no… Of course it wouldn’t work:
- If I add to cart for the first time and the ID and KEY match, I get the proper price and I’m good. If I delete the product from the cart, and re-add it with different ID, KEY and thus Price, it takes the previous price or the original from the product.
- If I try to add any product to cart without the parameters it’s not added. If I deactivate the plugin, it works.
For the love of God, I cannot understand what is wrong with the above code. I assume there must be something with the session but this would only explain the first point.
Any ideas, help are highly appreciated and needed. Even if I’m in a completely wrong direction.