I am trying to pass a parameter to a Woocommerce site using a URL – for instance:
site/?custom_p=77
will be the URL.
here is my code
add_filter('woocommerce_product_get_price', 'custom_price', 99, 2 );
add_filter('woocommerce_product_get_regular_price', 'custom_price', 99, 2 );
function custom_price( $cprice, $product ) {
// Delete product cached price (if needed)
wc_delete_product_transients($product->get_id());
// Get the data from the GET request
$custom_p=$_GET['custom_p'];
return ($custom_p) ;
}
URL add to cart site/?add-to-cart=455&custom_p=77
The problem when I declare the number 77
directly it works $custom_p=77
but $_GET['custom_p']
declaration gives as a result zero in cart.
3
Answers
Your GET variables get lost once URL changes, so all product prices get empty because also you are not targeting a the product that has been added to cart.
In this case you need to enable and use a WooCommerce Session variable to store the product ID and the custom price, when a
custom_p
GET variable is detected. Then you can use that WooCommerce Session variable to change the product price.First we detect and store the necessary data in a
WC_Session
variable:Then there is 2 ways to change the price of the product added to cart (choose only one)
Option 1 – Changing the product price directly:
Option 2 – Change the cart item price:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Option 1 gives a fatal error on WC admin. To fix that, I had to add
!is_admin()
to the if clause so it should look like this:Nice, it works even when dreamweaver says there is a syntax error in the first Part where the WC_Session variable is set: