Make the cart automatically add quantity to 0 to cart page in WooCommcerce - cart

I need my cart page to automatically add products to it when user visits the cart page with quantity 0, I tried to change it by:
I tried code 1 and code 2 with some variations but when I click on update cart the quantity get again to zero. For that product, although total remains the same.
What it should is the cart items wit zero quantities should not be removed when I update the cart and the quantity of that product which I changes from 0 to 1 should be get to 1.
Code 1
function add_product_to_cart_new() {
if ( ! is_admin() ) {
$product_id = array(2595,2594,1404,2650,1410,2652); //replace with your own product id
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if (in_array($_product->get_id(), $product_id))
//if ( $_product->get_id() == $product_id )
$found = true;
}
//if product not found, add it
if ( ! $found )
foreach($product_id as $ids ){
WC()->cart->add_to_cart( $ids);
}
} else {
//if no products in cart, add it
foreach($product_id as $ids ){
WC()->cart->add_to_cart( $ids);
}
}
}
}
And then below code (input_value) to make it zero on cart page.
Code 2
add_filter( 'woocommerce_quantity_input_args', 'jk_woocommerce_quantity_input_args', 10, 2 ); // Simple products
function jk_woocommerce_quantity_input_args( $args, $product ) {
//if ( is_singular( 'product' ) ) {
if( is_cart() ){
$args['input_value'] = 0; // Starting value (we only want to affect cart page)
}
//}
$args['max_value'] = 80; // Maximum value
$args['min_value'] = 0; // Minimum value
$args['step'] = 1; // Quantity steps
return $args;
}
Expected results like in this:
http://www.ecotechlube.com/cart/

This isn't perfect, but it is the only way I have found to do this.
First of all, you need to add product to cart with a magic small quantity, like this:
WC()->cart->add_to_cart($product_id, 0.00000001);
Then you need to make checks in cart and checkout templates like this:
if($cart_item['quantity'] == 0.00000001) $cart_item['quantity'] = 0;

Related

Delete specific product from cart depend on shipping method

On my woocommerce site, there are 2 shipping methods. Delivery and local pickup.
I use a code to add specific product to cart if the cart subtotal is under a value. If the subtotal is higher than the limit (in the code) the product will be removed.
Here is the code:
add_action( 'woocommerce_before_calculate_totals', 'adding_promotional_product', 10, 1 );
function adding_promotional_product( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$promo_id = 18625; // <=== <=== <=== Set HERE the ID of your promotional product
$targeted_cart_subtotal = 100000; // <=== Set HERE the target cart subtotal
$has_promo = false;
$subtotal = 0;
if ( ! $cart->is_empty() ){
// Iterating through each item in cart
foreach ($cart->get_cart() as $item_key => $cart_item ){
$product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
// If Promo product is in cart
if( $product_id == $promo_id ) {
$has_promo = true;
$promo_key= $item_key;
} else {
// Adding subtotal item to global subtotal
$subtotal += $cart_item['line_subtotal'];
}
}
// If Promo product is NOT in cart and target subtotal not reached, we add it.
if( ! $has_promo && $subtotal < $targeted_cart_subtotal ) {
$cart->add_to_cart( $promo_id );
// echo 'add';
// If Promo product is in cart and target subtotal is reached, we remove it.
} elseif( $has_promo && $subtotal > $targeted_cart_subtotal ) {
$cart->remove_cart_item( $promo_key );
}
}
}
The code is working good, but i would like to set this option for only 1 shipping method, which is the delivery. if customer would choose local pickup, it should delete it from the cart
Could someone help me how to resolve this?

how to load customer/group into Mage_Catalog_Model_Product_Type_Price

SOLVED By using Price Rules
i have changed the price scheme based on customer group by percentage. So here I do the trick for the product
if ($group->getCode() == "High ST. Shops") {
$percent = 100 - $_product->getHighstshopPerc();
$percent = "0." . $percent;
$srrp = $_product->getPrice() * $percent;
echo "Your Price £" . number_format($srrp, 2, '.', '');
}
Now I need getPrice() to come from price.php already with my new scheme so it adds to cart correctly. I tried the code below but i cant get getCode() to give me customer group so I can calculate/override getPrice
public function getPrice($product)
{
//$groupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
//$group = Mage::getModel('customer/group')->load($groupId);
//return $product->getData('price');
//return $product->getTradePerc();
//echo $product->getCode(); exit();
if ($product->getCode() == "NOT LOGGED IN")
return 1;
else return 2;
}

Magento Show parent and subcategories

How do I show on a category page in Magento only the parent category and subcategories?
When a subcategory is clicked the navigation has to stay the same.
Example:
If I have
Category 1
subcat 1
subcat 2
subcat 3
After clicking on any subcategory (say subcat 1), I want the same i.e :
Category 1
subcat 1
subcat 2
subcat 3
What I got now:
<?php
if (Mage::registry('current_category'))
{
echo Mage::registry('current_category')->getName();
}
?>
<?php
$currentCat = Mage::registry('current_category');
if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
{
// current category is a toplevel category
$loadCategory = $currentCat;
}
else
{
// current category is a sub-(or subsub-, etc...)category of a toplevel category
// load the parent category of the current category
$loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
// #TODO enhance for more nested category levels to display sub-categories
}
$subCategories = explode(',', $loadCategory->getChildren());
foreach ( $subCategories as $subCategoryId )
{
$cat = Mage::getModel('catalog/category')->load($subCategoryId);
if($cat->getIsActive())
{
echo ''.$cat->getName().' ';
}
}
?>
But of course this isn't working correct but I can't find a good solution so that Category 1 stays the same when I press subcat 1.
And it would be wonderful if the selected subcategory would be bold.
In your code, in place of
<?php
if (Mage::registry('current_category'))
{
echo Mage::registry('current_category')->getName();
}
?>
Try using
<?php
function getParentTopCategory($c)
{
if($c->getLevel() == 2){
return $c;
} else {
$parentCategory = Mage::getModel('catalog/category')->load($c->getParentId());
return getParentTopCategory($parentCategory);
}
}
if (Mage::registry('current_category'))
{
$category = Mage::registry('current_category');
$t = getParentTopCategory($category);
echo $t->getName();
}
?>
It should work.
EDIT:
Here is your complete solution :-
$crcat = Mage::registry('current_category')->getName(); //The current category name is stored in $crcat
function getParentTopCategory($c)
{
if($c->getLevel() == 2){
return $c;
} else {
$parentCategory = Mage::getModel('catalog/category')->load($c->getParentId());
return getParentTopCategory($parentCategory);
}
}
if (Mage::registry('current_category'))
{
$category = Mage::registry('current_category');
$t = getParentTopCategory($category);
if($crcat == $t->getName()) //Check if current category is the topmost category
echo "<b>".$t->getName()."</b>"; //If yes display it as bold (Currently Selected)
else //
echo $t->getName(); //Otherwise display it as normal
echo "<br>";
}
?>
<?php
$currentCat = Mage::registry('current_category');
if ( $currentCat->getParentId() == Mage::app()->getStore()->getRootCategoryId() )
{
// current category is a toplevel category
$loadCategory = $currentCat;
}
else
{
// current category is a sub-(or subsub-, etc...)category of a toplevel category
// load the parent category of the current category
$loadCategory = Mage::getModel('catalog/category')->load($currentCat->getParentId());
// #TODO enhance for more nested category levels to display sub-categories
}
$subCategories = explode(',', $loadCategory->getChildren());
foreach ( $subCategories as $subCategoryId )
{
$cat = Mage::getModel('catalog/category')->load($subCategoryId);
if($cat->getIsActive())
{
if($crcat == $cat->getName()) //Check if current category is this subcategory
echo '<b>'.$cat->getName().'</b>'.'</br>'; //If yes display it as bold (Currently Selected)
else //
echo ''.$cat->getName().''.'</br>'; //Otherwise display it as normal
}
}

Magento partial refund programmatically

How can i create partial create memo? i.e. if total order value is £50 and I want to create a credit memo of £10. I am using the below code to create credit memo:
function createCreditMemo($orderId) {
$order = Mage::getModel('sales/order')->load($orderId, 'increment_id');
if (!$order->getId()) {
print_r('order_not_exists');
}
if (!$order->canCreditmemo()) {
Mage::log('cannot_create_creditmemo', null, 'product.txt');
print_r('cannot_create_creditmemo');
}
$data = array();
$refundToStoreCreditAmount = '10.22';
$service = Mage::getModel('sales/service_order', $order);
$creditmemo = $service->prepareCreditmemo($data);
// refund to Store Credit
if ($refundToStoreCreditAmount) {
// check if refund to Store Credit is available
if ($order->getCustomerIsGuest()) {
print_r('cannot_refund_to_storecredit');
}
$refundToStoreCreditAmount = max(
0,
min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
);
if ($refundToStoreCreditAmount) {
$refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
$creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
$refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
$refundToStoreCreditAmount*$order->getStoreToOrderRate()
);
// this field can be used by customer balance observer
$creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
// setting flag to make actual refund to customer balance after credit memo save
$creditmemo->setCustomerBalanceRefundFlag(true);
print_r($refundToStoreCreditAmount.'<br/>');
//die('2');
}
}
//Mage::log($creditmemo, null, 'product.txt');
$creditmemo->setPaymentRefundDisallowed(true);
$creditmemo->register();
$orderCreditMemoStatusCode = Mage_Sales_Model_Order::STATE_CLOSED;
$orderCreditMemoStatusComment = 'Order Refunded.';
$saveTransaction = Mage::getModel('core/resource_transaction')->addObject ($creditmemo )->addObject ( $order )->save ();
$order->addStatusToHistory ( $orderCreditMemoStatusCode, $orderCreditMemoStatusComment, true );
$notifyCustomer = true;
$comment = 'testing refund';
$includeComment = true;
$creditmemo->setEmailSent(true);
// add comment to creditmemo
if (!empty($comment)) {
$creditmemo->addComment($comment, $notifyCustomer);
}
try {
Mage::getModel('core/resource_transaction')
->addObject($creditmemo)
->addObject($order)
->save();
// send email notification
$creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
} catch (Mage_Core_Exception $e) {
print_r('data_invalid', $e->getMessage());
}
echo $creditmemo->getIncrementId();
}
In the below code, even if I set the $refundToStoreCreditAmount = 10; it still refunds the full amount. Any idea how to refund partially?

Magento 1 - get category ID from product ID

In magento how to get the category id of each product from its product ID.
$items = $request->getAllItems();
$c = count($items);
for ($i = 0; $i < $c; $i++) {
if ($items[$i]->getProduct() instanceof Mage_Catalog_Model_Product) {
if ($items[$i]->getProduct()->getId()) {
$this->_dhlAllowed = false;
}
}
}
Here $items[$i]->getProduct()->getId() returns product ID. I want its category ID.
public function getProductCategory() {
/* #var $product Mage_Catalog_Model_Product */
$product = Mage::registry('current_product');
if ($product->getId()) {
$categoryIds = $product->getCategoryIds();
if (is_array($categoryIds) and count($categoryIds) >= 1) {
return Mage::getModel('catalog/category')->load($categoryIds[0]);
};
}
return false;
}
Mage::registry('current_product')->getCategoryId();
this way, category id of a current product can be get.
suppose if you want all category ids from current product id you can get from
Mage::registry('current_product')->getCategoryIds();
it may help you

Resources