I have a custom add to cart button in php for a single product:
Final total<br>
$<?php echo $row['purchase-price'] ?>.00<br><br>
<button onclick="window.location.href='https://yourdomain.com/checkout/?add-to-cart=362166';">Add to cart</button>
After clicking the button, it returned a "Sorry, this product cannot be purchased." error. I havent set the product price since the amount in <?php echo $row['purchase-price'] ?> is always changing. How to pass the amount set in php and pass it to product's final price?
First you will restrict your code to single product and archives pages only:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
if( is_shop() || is_product_category() || is_product_tag() || is_product() ) {
global $wpdb;
//your query to get price from custom db
//FOR GET PRODUCT ID $product->get_id();
$price = $row['purchase-price'];
}
return $price;
}
Then for cart and checkout pages, you will change the cart item price this way:
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
global $wpdb;
//your query to get price from custom db
$new_price = $row['purchase-price'];
//FOR GET PRODUCT ID $cart_item['data']->get_id();
// Set and register the new calculated price
$cart_data['data']->set_price( $new_price );
$cart_data['new_price'] = $new_price;
return $cart_data;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
return $session_data;
// Get the new calculated price and update cart session item price
$session_data['data']->set_price( $session_data['new_price'] );
return $session_data;
}
And in the last hit your custom url
<button onclick="window.location.href='https://yourdomain.com/?add-to-cart=362166&quantity=1';">Add to cart</button>
Related
I am developing a wordpress and woocommerce-based website where information on cooking-related training is provided and various kitchen materials are sold.
Those who want to participate in the trainings apply by filling out a form. Kitchen supplies are also sold through woocommerce.
Trainings are added to the website with a type of content called training.
Some trainings are requested to be sold over the woocommerce structure. However, these "Trainings" that want to be sold are wanted to remain in the form of educational content. In addition, it is requested not to be added or moved as a product.
First of all, I created a virtual product called Education. I hid the product in the store.
Then I added a custom field for Tutorials called price. The price of each training to be sold will be entered here.
I have a button "Register for Training" on the training detail page, I changed it to "Buy" for the trainings wanted to sell and the link
?add-to-cart=340&custom_price=600&quantity=1
I gave in the form.
Here 340 is the id of the virtual product I created.
When the Buy button is clicked, the virtual product called Education is added to the basket. But I want to update the name and price of this training according to which training detail page is printed.
The codes I added to functions.php.
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals' );
function before_calculate_totals( $_cart ){
// loop through the cart_contents
foreach ( $_cart->cart_contents as $cart_item_key => &$item ) {
// you will need to determine the product id you want to modify, only when the "donation_amount" is passed
if ( $item['product_id'] == 340 && isset( $_GET['custom_price'] ) ){
// custom price from POST
$custom_price = $_GET['custom_price'] > 0 ? $_GET['custom_price'] : 0;
// save to the cart data
//$item['data']->price = $custom_price;
// new versions of WooCommerce may require (instead of line above)...
$item['data']->set_price($custom_price);
}
}
}
function ipe_product_custom_price( $cart_item_data, $product_id ) {
if( isset( $_POST['custom_price'] ) && !empty($_POST['custom_price'])) {
$cart_item_data[ "custom_price" ] = $_POST['custom_price'];
}
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'ipe_product_custom_price', 99, 2 );
I wanted to update the price with these codes, but it didn't work.
How do I dynamically update the information of the virtual product? Or what different method would you suggest?
There are some mistakes in your code and some missing things to make it work. Try the following:
// Set custom data as custom cart data in the cart item
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_price_as_custom_cart_item_data', 30, 3 );
function add_custom_price_as_custom_cart_item_data( $cart_item_data, $product_id, $variation_id ) {
if( ! isset($_GET['custom_price']) ) {
$cart_item_data['custom_price'] = (float) esc_attr( $_GET['custom_price'] );
$cart_item_data['unique_key'] = md5( microtime().rand() ); // Make each item unique
}
return $cart_item_data;
}
// Change cart item price
add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price' );
function change_cart_item_price( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// loop through the cart_contents
foreach ( $cart->get_cart() as $cart_item ) {
// you will need to determine the product id you want to modify, only when the "donation_amount" is passed
if ( isset($cart_item['custom_price']) ) {.
$item['data']->set_price($cart_item['custom_price']);
}
}
}
// Display the custom price on minicart too
add_filter( 'woocommerce_cart_item_price', 'change_minicart_item_price', 10, 3 );
function change_minicart_item_price( $price_html, $cart_item, $cart_item_key ) {
if( ! is_cart() && isset( $cart_item['custom_price'] ) ) {
$args = array( 'price' => floatval($cart_item['custom_price']) );
if ( WC()->cart->display_prices_including_tax() ) {
$product_price = wc_get_price_including_tax( $cart_item['data'], $args );
} else {
$product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
}
return wc_price( $product_price );
}
return $price_html;
}
Code goes in functions.php file of your active child theme (or active theme). It should works.
In Woocommerce, I used jQuery to calculate a custom price on a single product pages, and now need to pass this value to the cart.
The desired behavior is to pass the new price retrieved from the hidden field to the cart item price.
Here is my actual code:
// Hidden input field in single product page
add_action( 'woocommerce_before_add_to_cart_button', 'custom_hidden_product_field', 11, 0 );
function custom_hidden_product_field() {
echo '<input type="hidden" id="hidden_field" name="custom_price" class="custom_price" value="">';
}
// The code to pass this data to the cart:
add_action( 'woocommerce_add_cart_item_data', 'save_custom_fields_data_to_cart', 10, 2 );
function save_custom_fields_data_to_cart( $cart_item_data, $product_id ) {
if( ! empty( $_REQUEST['custom_price'] ) ) {
// Set the custom data in the cart item
$cart_item_data['custom_data']['custom_price'] = $_REQUEST['custom_price'];
$data = array( 'custom_price' => $_REQUEST['custom_price'] );
// below statement make sure every add to cart action as unique line item
$cart_item_data['custom_data']['unique_key'] = md5( microtime().rand() );
WC()->session->set( 'custom_data', $data );
}
return $cart_item_data;
}
And check both $data and $cart_item_data to see that they both return the custom_price data that is calculated on the page.
However, I go to view cart, and the value of the line item is still 0.
I set a var equal to the WC()->session->set( 'custom_data', $data ); and then var_dump to check it, but this returns NULL which might just be what it returns, I'm not entirely sure because I've never used it.
I should also add that I have the regular_price in the product backend set to 0. When I erase this (and leave it blank) I get back the error:
Warning: A non-numeric value encountered in
C:\xampp\htdocs\my-transfer-source\wp-content\plugins\woocommerce\includes\class-wc-discounts.php on line 85
I'm wondering if I've missed something here, and if someone could lend some light onto this? Thanks
Update 2021 - Handling custom price item in mini cart
First for testing purpose we add a price in the hidden input field as you don't give the code that calculate the price:
// Add a hidden input field (With a value of 20 for testing purpose)
add_action( 'woocommerce_before_add_to_cart_button', 'custom_hidden_product_field', 11 );
function custom_hidden_product_field() {
echo '<input type="hidden" id="hidden_field" name="custom_price" class="custom_price" value="20">'; // Price is 20 for testing
}
Then you will use the following to change the cart item price (WC_Session is not needed):
// Save custom calculated price as custom cart item data
add_filter( 'woocommerce_add_cart_item_data', 'save_custom_fields_data_to_cart', 10, 2 );
function save_custom_fields_data_to_cart( $cart_item_data, $product_id ) {
if( isset( $_POST['custom_price'] ) && ! empty( $_POST['custom_price'] ) ) {
// Set the custom data in the cart item
$cart_item_data['custom_price'] = (float) sanitize_text_field( $_POST['custom_price'] );
// Make each item as a unique separated cart item
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
// For mini cart
add_action( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 2 );
function filter_cart_item_price( $price, $cart_item ) {
if ( isset($cart_item['custom_price']) ) {
$args = array( 'price' => floatval( $cart_item['custom_price'] ) );
if ( WC()->cart->display_prices_including_tax() ) {
$product_price = wc_get_price_including_tax( $cart_item['data'], $args );
} else {
$product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
}
return wc_price( $product_price );
}
return $price;
}
// Updating cart item price
add_action( 'woocommerce_before_calculate_totals', 'change_cart_item_price', 30, 1 );
function change_cart_item_price( $cart ) {
if ( ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Set the new price
if( isset($cart_item['custom_price']) ){
$cart_item['data']->set_price($cart_item['custom_price']);
}
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
I am trying to set the functionality in Woocommerce on the Add to Cart button to only allow a particular product to be added once to the Cart.
Once a particular product has been added to cart the first time, the Add to Cart needs to be hidden.
In the cart I can have any number of products - just a max of quantity 1 for each product.
I was doing research and saw that I can use woocommerce_add_to_cart_validation hook. But have no idea how to start off.
How can I allow a particular product to be added once to the Cart?
Disable add to cart button if product is in cart using woocommerce_is_purchasable hook:
add_filter( 'woocommerce_is_purchasable', 'disable_add_to_cart_if_product_is_in_cart', 10, 2 );
function disable_add_to_cart_if_product_is_in_cart ( $is_purchasable, $product ){
// Loop through cart items checking if the product is already in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $cart_item['data']->get_id() == $product->get_id() ) {
return false;
}
}
return $is_purchasable;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works (even for product variations in variable products).
Original answer:
Here is an example using woocommerce_add_to_cart_validation hook and that will do the trick (preventing add to cart action and displaying a custom notice when needed), and using a custom utility function that will remove quantity field for your specific defined product ID:
add_filter( 'woocommerce_add_to_cart_validation', 'limit_cart_items_from_category', 10, 3 );
function limit_cart_items_from_category ( $passed, $product_id, $quantity ){
// HERE define your product ID
$targeted_product_id = 37;
// Check quantity and display notice
if( $quantity > 1 && $targeted_product_id == $product_id ){
wc_add_notice( __('Only one item quantity allowed for this product', 'woocommerce' ), 'error' );
return false;
}
// Loop through cart items checking if the product is already in cart
foreach ( WC()->cart->get_cart() as $cart_item ){
if( $targeted_product_id == $product_id && $cart_item['data']->get_id() == $targeted_product_id ) {
wc_add_notice( __('This product is already in cart (only one item is allowed).', 'woocommerce' ), 'error' );
return false;
}
}
return $passed;
}
// Checking and removing quantity field for a specific product
add_filter( 'woocommerce_quantity_input_args', 'custom_quantity_input_args', 10, 2 );
function custom_quantity_input_args( $args, $product ) {
// HERE define your product ID
$targeted_product_id = 37;
if( $targeted_product_id == $product->get_id() )
$args['min_value'] = $args['max_value'] = $args['input_value'] = 1;
return $args;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
in our Woocommerce store we have some minimum price for any products . And in every product inner page there is two filed where customer can type width , height of the product . And then they can add this product to cart, then price is changed based on given width and height.
For example if the minimum price for a product is 50 . And customer add width =2, height=3 , then the price for this product is going to 50*2*3=300
So to arrange this we add this code to function.php
add_filter( 'woocommerce_add_cart_item', 'add_custom_cart_item_data', 10, 2 );
function add_custom_cart_item_data( $cart_item_data, $cart_item_key ) {
$result=$_POST['width']*$_POST['height']*$cart_item_data['data']->price;
$cart_item_data['new-price'] =$result;
$cart_item_data['data']->set_price($result);
return $cart_item_data;
}
So this is working correctly .
But the problem is once it is coming to checkout page then the product price is showing as 50 , but it is 300 actually.
so to overcome this i use the following code
add_filter( 'woocommerce_cart_item_subtotal', 'update_with_custom_details', 10, 3 );
function update_with_custom_details( $subtotal, $cart_item, $cart_item_key ) {
$subtotal =" £".$cart_item['line_total'];
return $subtotal;
}
now it is showing £300, but i know this code is wrong.
The code is wrong because when customer apply a 50% coupon code for this product then the discount is coming as 25 , Because it calculating based on 50*.5=25; But actually product new price is 300, so the discount should be 300*5=150;
So how i can update the product price in cart page, checkout page ,mini cart etc ?
Please help .
Please see this also
Woocommerce product custom price is not accepted by wocommerce coupon
Update 2: The correct way to do it need to be done in two steps:
We calculate the price on add to cart event hook and save it as custom cart item data.
We set that calculated price in woocommerce_before_calculate_totals hook
The code:
// Save custom field value in cart item as custom data
add_filter( 'woocommerce_add_cart_item_data', 'calculate_custom_cart_item_prices', 30, 3 );
function calculate_custom_cart_item_prices( $cart_item_data, $product_id, $variation_id ) {
if ( isset($_POST['width']) && isset($_POST['height']) ) {
// Get the correct Id to be used (compatible with product variations)
$the_id = $variation_id > 0 ? $variation_id : $product_id;
$product = wc_get_product( $the_id ); // Get the WC_Product object
$product_price = (float) $product->get_price(); // Get the product price
// Get the posted data
$width = (float) sanitize_text_field( $_POST['width'] );
$height = (float) sanitize_text_field( $_POST['height'] );
$new_price = $width * $height * $product_price; // Calculated price
$cart_item_data['calculated-price'] = $new_price; // Save this price as custom data
}
return $cart_item_data;
}
// Set custom calculated price in cart item price
add_action( 'woocommerce_before_calculate_totals', 'set_calculated_cart_item_price', 20, 1 );
function set_calculated_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ){
if( ! empty( $cart_item['calculated-price'] ) ){
// Set the calculated item price (if there is one)
$cart_item['data']->set_price( $cart_item['calculated-price'] );
}
}
}
Code goes in function.php file of your active child theme (or theme). Tested and works.
For testing purpose, I have used the following code that output 2 custom fields on single product pages:
// The hidden product custom field
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
function add_gift_wrap_field() {
global $product;
// The fake calculated price
?>
<div>
<label class="product-custom-text-label" for="servicetime"><?php _e( 'Custom text:', 'woocommerce'); ?><br>
<input type="text" id="user-width" name="width" value=""><br>
<input type="text" id="user-height" name="height" value="">
</label>
</div><br>
<?php
}
I need to double the price for every product in Woocommerce frontend. For this I used the following code:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
return $price*2;
}
But there is an error using this code. checkout page price is not correct.
for example the product orginal price is 10. We double the price by this code . so the product price is 20 now. When i added this product to the cart then cart and checkout page price is 40. That means this multiplication is take place in two times.
Please help to solve this.
Updated To double the price:
1) First you will restrict your code to single product and archives pages only:
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
if( is_shop() || is_product_category() || is_product_tag() || is_product() )
return $price*2;
return $price;
}
2) Then for cart and checkout pages, you will change the cart item price this way:
add_filter( 'woocommerce_add_cart_item', 'set_custom_cart_item_prices', 20, 2 );
function set_custom_cart_item_prices( $cart_data, $cart_item_key ) {
// Price calculation
$new_price = $cart_data['data']->get_price() * 2;
// Set and register the new calculated price
$cart_data['data']->set_price( $new_price );
$cart_data['new_price'] = $new_price;
return $cart_data;
}
add_filter( 'woocommerce_get_cart_item_from_session', 'set_custom_cart_item_prices_from_session', 20, 3 );
function set_custom_cart_item_prices_from_session( $session_data, $values, $key ) {
if ( ! isset( $session_data['new_price'] ) || empty ( $session_data['new_price'] ) )
return $session_data;
// Get the new calculated price and update cart session item price
$session_data['data']->set_price( $session_data['new_price'] );
return $session_data;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and working. It will change all prices as you expect in cart, checkout and order pages…