I use the code below for changing the price into the Magento cart dynamic.
class Test_Pricecalc_Model_Observer
{
public function modifyPrice(Varien_Event_Observer $obs)
{
// Get the quote item
$item = $obs->getQuoteItem();
// Ensure we have the parent item, if it has one
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
// Load the custom price
$price = $this->_getPriceByItem($item);
// Set the custom price
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
// Enable super mode on the product.
$item->getProduct()->setIsSuperMode(true);
}
protected function _getPriceByItem(Mage_Sales_Model_Quote_Item $item)
{
$price = $price + 10;
return $price;
}
protected function _getRequest()
{
return Mage::app()->getRequest();
}
}
Does someone now how to get the custom price from the product detail page after choosing the product options there? I want to use that price as basis price fur my further calculation.
You can create a hidden input field in product detail page with value equal to your custom price.
and can get that field in your observer like:
$new_price = Mage::app()->getRequest()->getPost('custom_price');
where 'custom_price' is the name of your hidden field and $new_price in oberserver is your custom price.
here is an example, which we used to render our product price during "add to cart":-
class Tech9_Myprice_Model_Observer
{
public function modifyPrice(Varien_Event_Observer $obs)
{
// Get the quote item
$item = $obs->getQuoteItem();
// Ensure we have the parent item, if it has one
$item = ( $item->getParentItem() ? $item->getParentItem() : $item );
// Load the custom price
$new_price = Mage::app()->getRequest()->getPost('custom_price');
Mage::log( $new_price);
$price = $new_price;
// Set the custom price
$item->setCustomPrice($price);
$item->setOriginalCustomPrice($price);
// Enable super mode on the product.
$item->getProduct()->setIsSuperMode(true);
}
}
Here Tech9 is the name of our package and Myprice is the name of our module.
We had to use our custom price during "add to cart" event. We prepared a separate module for it , if you like we can provide you with that package as well.
Related
I want get and set log for woocommerce variation product price after product price change. (after click on update product)
EX :
Product 1 :
Variation 1 : old price : 10.000 , new price : 20.000
Variation 2 : old price : 30.000 , new price : 50.000
i test wp_insert_post_data filter and save_post_product action
but i can't get old price and two function return new price
How i can get product old price before new price saved in database
**die at the end of function for see result.
add_action('save_post_product', 'save_post_action', 10, 3);
function save_post_action( $post_id, $post, $update ) {
if (get_post_type($post_id) !== 'product') return;
$product = wc_get_product($post_id);
$current_products = $product->get_children();
foreach ($current_products as $variation_id) {
$variable_product = wc_get_product($variation_id);
//$regular_price = $variable_product->get_regular_price();
//$sale_price = $variable_product->get_sale_price();
$price = $variable_product->get_price();
var_dump($price);
}
die;
}
Variable products are saved using Ajax before saving the parent.
So woocommerce_admin_process_variation_object action precedes save product variation.
add_action('woocommerce_admin_process_variation_object', 'get_previous_variation_price', 10, 1);
function get_previous_variation_price($variation) {
$previous_price = $variation->get_price();
}
I have written this to extract the product variation prices
global $product;
if ( $product->is_type('variable') ) {
function get_product_variation_price($variation_id) {
global $woocommerce;
$product = new WC_Product_Variation($variation_id);
return $product->get_price_html();
}
$product_variations = $product->get_available_variations();
$arr_variations_id = array();
foreach ($product_variations as $variation) {
$product_variation_id = $variation['variation_id'];
$product_price = get_product_variation_price($product_variation_id);
}
$amount = get_product_variation_price($product_variation_id);
} else {
$amount = str_replace(".", ",", $product->get_price());
}
What I am trying to achieve is that if the product is a variable product, the amount variable changes to what currently selected variants set price is, however, this will always get me the first variants price. How can I achieve that?
I don't see any reason to create a plugin for showing variation prices because this is the default from woocommerce. Can you share why are you creating this plugin? Does the default function not work on your site? If you are only looking to change decimals for prices, you can change these settings from currency options.
I've coded in a custom select box to a group of my products that changes the price based on the user's selection. It works well, but now I need to change the product title too based on their selection.
Basically if option 1 is chosen, the product name stays the same. But is option 2 is chosen, I need to add "-RZ" to the end of the product title.
I'm not sure if I can do this in the 'woocommerce_before_calculate_totals' hook where I altered the prices, but if anyone knows the hook I should use and the code to access the current product's title via PHP that would be great.
Here is the code that alters the price if it's helpful:
function calculate_core_fee( $cart_object ) {
if( !WC()->session->__isset( "reload_checkout" )) {
/* core price */
//echo $additionalPrice;
//$additionalPrice = 100;
foreach ( $cart_object->cart_contents as $key => $value ) {
$product_id = $value['product_id'];
if( isset( $value["addOn"] ) && $value["addOn"] == $product_id) {
$additionalPrice = $value['core'];
/* Woocommerce 3.0 + */
$orgPrice = floatval( $value['data']->get_price() );
//echo $additionalPrice;
//echo $orgPrice;
$value['data']->set_price( $orgPrice + $additionalPrice );
}
}
}
}
add_action( 'woocommerce_before_calculate_totals', 'calculate_core_fee', 99 );
I know may have to get the name and store it in a SESSION variable to use later if the hook to do this is on the cart, checkout, or order page rather than the single-product page.
Yes this is possible in the same hook. You can manipulate the product title with class WC_Product get_name() and set_name() methods. But as for the price, you should set and get a custom cart field value to make it (just as $additionalPrice = $value['core'];).
See here a simple related answer: Changing WooCommerce cart item names
So you could have something like (just a fake example):
// Get your custom field cart value for the user selection
$userSelection = $value['user_selection'];
// Get original title
$originalTitle = $value['data']->get_name();
// Conditionally set the new item title
if($userSelection == 'option2')
$value['data']->set_name( $originalTitle . '-RZ' );
Hi for a Magento website i need to load a custom attribute in the shopping cart.
i use getmodel function to load the items. but i have no clue how i load the attribute. maybe i haven't configure the attribute right. i have enabled yes for enable on product listing. de attribute code is 'staffel_percentage'. it is just a regular string
also when i change the price per product it doesn't change the subtotal maybe this is because we already change the price for the product on the rest of the website?
maybe it is in the event? i use this event: controller_action_layout_render_before.
this is the code in observer i use for it
$cart = Mage::getModel('checkout/cart')->getQuote(); // Gets the collection of checkout
foreach ($cart->getAllItems() as $item) { // adds all items to $item and does the following code for each item
if ($item->getParentItem()) { // If items is part of a parent
$item = $item->getParentItem(); // Get parentItem;
}
//echo 'ID: '.$item->getProductId().'<br />';
$percentage = 80;// init first percentage
$quantity = $item->getQty(); //quantity
//$staffelstring = loadattribute//loads attribute
//gives the right percentage per quantity
//$staffelarray = explode(';', ^);
//foreach($staffelarray as $staffels){
//$stafel = explode(':', $staffels);
//if($quantity >= $stafel[0]){
//$percentage = $Stafel[1];
//}
//}
$currency = Mage::app()->getStore()->getCurrentCurrencyRate(); // Currencyrate that is used currently
$specialPrice = (($this->CalculatePrice($item) * $currency)* $percentage) / 100; //New prices we want to give the products
if ($specialPrice > 0) { // Check if price isnt lower then 0
$item->setCustomPrice($specialPrice); //Custom Price will have our new price
$item->setOriginalCustomPrice($specialPrice); //Original Custom price will have our new price, if there was a custom price before
$item->getProduct()->setIsSuperMode(true); //set custom prices against the quote item
}
}
You need to load the product right after your first if statement
$product = Mage::getModel('catalog/product')->load($item->getId()); // may be $item->getProductId() instead here
Then on the next line after that you can add some logging statements that will appear in var/log/system.log
Mage::log($product->getData()); // this will output all of the product data and attributes. You will see your custom attribute value here if it is set on this product.
If there is a value set for your product for your custom attribute then you can get it like this
$value = $product->getData('staffel_percentage');
As for the prices changing, not sure how you have the prices set up. You need to set a positive or negative number to add or subtract from the price in the fields found in the parent product configuration page in Catalog > Products > Your product > Associated Products.
See this image for what the section looks like.
I want to add a product to cart programmatically. Also, I want to change the product price when added to cart.
Suppose, my product's price is $100. I wanted to change it to $90 when added to cart.
I added product to cart. However, I am unable to change the product price.
Is it possible?
Here is the code to add product to cart:-
$cart = Mage::getSingleton('checkout/cart');
try {
$cart->addProduct($product, array('qty' => 1));
$cart->save();
}
catch (Exception $ex) {
echo $ex->getMessage();
}
After digging a bit into Magento's core code, I found that you need to use $item->getProduct()->setIsSuperMode(true) in order to make $item->setCustomPrice() and $item->setOriginalPrice() work.
Here is some sample code you can use within an Observer that listens for the checkout_cart_product_add_after or checkout_cart_update_items_after events. The code is logically the same except checkout_cart_product_add_after is called for only one item and checkout_cart_update_items_after is called for all items in the cart. This code is separated/duplicated into 2 methods only as an example.
Event: checkout_cart_product_add_after
/**
* #param Varien_Event_Observer $observer
*/
public function applyDiscount(Varien_Event_Observer $observer)
{
/* #var $item Mage_Sales_Model_Quote_Item */
$item = $observer->getQuoteItem();
if ($item->getParentItem()) {
$item = $item->getParentItem();
}
// Discounted 25% off
$percentDiscount = 0.25;
// This makes sure the discount isn't applied over and over when refreshing
$specialPrice = $item->getOriginalPrice() - ($item->getOriginalPrice() * $percentDiscount);
// Make sure we don't have a negative
if ($specialPrice > 0) {
$item->setCustomPrice($specialPrice);
$item->setOriginalCustomPrice($specialPrice);
$item->getProduct()->setIsSuperMode(true);
}
}
Event: checkout_cart_update_items_after
/**
* #param Varien_Event_Observer $observer
*/
public function applyDiscounts(Varien_Event_Observer $observer)
{
foreach ($observer->getCart()->getQuote()->getAllVisibleItems() as $item /* #var $item Mage_Sales_Model_Quote_Item */) {
if ($item->getParentItem()) {
$item = $item->getParentItem();
}
// Discounted 25% off
$percentDiscount = 0.25;
// This makes sure the discount isn't applied over and over when refreshing
$specialPrice = $item->getOriginalPrice() - ($item->getOriginalPrice() * $percentDiscount);
// Make sure we don't have a negative
if ($specialPrice > 0) {
$item->setCustomPrice($specialPrice);
$item->setOriginalCustomPrice($specialPrice);
$item->getProduct()->setIsSuperMode(true);
}
}
}
Magento have changed the way the prices are calculated in the cart which makes it very difficult to do this in v1.4 onwards. If you do set the price using an Observer or other device, it will almost certainly be overwritten back to the catalog price.
Effectively, you need to use Shopping Cart rules to implement this.
It is possible to set a customer specific price of a quote item. Hence, something like this should do it:
$quoteItem = $quote->addProduct($product, $qty);
$quoteItem->setCustomPrice($price);
// we need this since Magento 1.4
$quoteItem->setOriginalCustomPrice($price);
$quote->save();
Hope this helps...
Jonathan's answer is likely the best for most situations. But some customers might not like how shopping cart discounts are displayed in the cart. I recently did a project (with Magento 1.3.3) where the customer didn't like how the each line item still showed the full price as well as the subtotal, with a Discount line below the subtotal - he wanted to see the price of each item discounted, and the subtotal show the discounted price as well. He really didn't like having the Discount line after the Subtotal line.
Anyway, if you find yourself in the same boat, one approach is to override the getCalculationPrice() and getBaseCalculationPrice() methods in Mage_Sales_Model_Quote_Address_Item and Mage_Sales_Model_Quote_Item. I know that it isn't always pretty to override, much better to use events, but in this case I couldn't get events to work seamlessly on both the frontend and backend. Not sure if this approach will work in Magento 1.4+.
If I have to share my solution that I made on the base of Simon then I have managed to rewrite model class save function of quote.
public function save()
{
$this->getQuote()->getBillingAddress();
$this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
$this->getQuote()->collectTotals();
//$this->getQuote()->save();
foreach($this->getQuote()->getAllItems() as $item) {
$productId = $item->getProductId();
$product = Mage::getModel('catalog/product')->load($productId);
if($product->getAttributeText('is_dummy') == 'Yes') {
$price = 2;
$item->setCustomPrice($price);
// we need this since Magento 1.4
$item->setOriginalCustomPrice($price);
}
}
$this->getQuote()->save();
$this->getCheckoutSession()->setQuoteId($this->getQuote()->getId());
/**
* Cart save usually called after chenges with cart items.
*/
Mage::dispatchEvent('checkout_cart_save_after', array('cart'=>$this));
return $this;
}
I had the same issue and i am not a developer. What i did was added a new price attribute in magento backend called "site price". On the product page this showed the higher price $100. the actual price of the item was $90. so when the shopper adds it to cart they will see the actual price of the item, but on the product page they see the custom attribute price of $100
if all your prices on the product page are a set % higher then the real price just multiply your product price by the 1+percent. So if you want to add 10% to all your prices do price*1.1
This will display your price as 10% higher but when the shopper adds to cart they will see the real price.