php – Cart total Weight and Shipping Recalculation on WooCommerce

I’m trying to use a snippet to add my custom boxes weight to the total order weight and the total height of the order in the basket. It is currently working to display the calculated total order weight at the checkout in addition to the box weight.

However, the shipping methods are not recalculated to display the correct shipping price based on the recalculated weight of the snippet. What do I need to add to recalculate shipping based on the weight calculation of the snippet?

 add_filter( 'woocommerce_cart_contents_weight', 'filter_wc_cart_contents_weight', 10000 );
    function filter_wc_cart_contents_weight( $weight ) {
        //box testing sizes (kg)
        $Envelope = 2;
        $Small_parcel = 10;
        $Medium_parcel = 50;
    
        // Loop through cart items
        foreach(WC()->cart->get_cart() as $cart_item ) {
            $total_height += $cart_item('data')->get_height() * $cart_item('quantity');
            }
        if( $total_height <= 8)  {
                $weight += $Envelope;
        }
        if( $total_height >= 8 && $total_height <=61)  {
                $weight += $Small_parcel;
        }
        return $weight;
    }
    
    
    //show calculated weight at checkout
    
    add_action( 'woocommerce_cart_totals_after_order_total', 'display_wc_cart_total_weight_after_order_total' );
    function display_wc_cart_total_weight_after_order_total() {
        ?>
        <tr class="order-total">
            <th><?php esc_html_e( 'Total weight', 'woocommerce' ); ?></th>
            <td data-title="<?php esc_attr_e( 'Total weight', 'woocommerce' ); ?>"><?php echo wc_format_weight( WC()->cart->get_cart_contents_weight() ); ?></td>
        </tr>
        <?php

}

exclude product from cart spend restrictions: yith-woocommerce

I’m using a minimum-maximum plugin for woocommerce from yith. say I have 3 categories of paper, pens, and mugs. paper generally costs $10, pens generally $5, and mugs generally $50.

now I set a cart spend minimum of $100 but I want to exclude pens from the cart spend minimum. even after setting it up in the backend, I still cannot checkout pens because it claims the cart spend of $100 has not been reached.

if anyone has experienced this and has a workaround, please help.

magento2 – Product package with quantity 0 continues to appear in the cart

Guys I need help with something in magento, I look everywhere and I couldn’t solve it and since I’m a novice I decided to resort to you. On the page of bundle products when setting the input of a product to 0 and clicking on buy it continues to appear in the cart. How can I solve this? I need to resolve this and I need help.

enter image description here

enter image description here

javascript – Woocommerce add to cart button does not update cart

Good evening. Your help please. I have created a page in the latest version of wordpress 5.7.1 and woocommerce 5.2.2 and I am facing the following problem.
On the product page, when I click on add to cart, the product does not enter the cart.
do a quick loading of the cart and the quantity remains zero.
From the categories page from the product thumbnail if I click add to cart the product is normally added to the cart.
I have disabled everything except the woocommerce plug in and I am working on the theme storefront.
I also quote the link https://hug.gr/product/red-football/ if you can help me I would be grateful. thank you

magento2 – Magento 2.4.2. Mini cart count not updating after free product remove on update cart button click

When total price is above $200 cart price rule is applied and free products are added to the cart.
enter image description here

when total price is below $200, cart price rule is applied and free products are removed from the cart after we decrease quantity and click update cart button. But the minicart count doesnt decrease.

enter image description here

The items are being removed through the ‘sales_quote_save_after’ event and observer:

class SamplesRemoveExtra implements ObserverInterface
{
    protected $checkoutSession;
    protected $itemModel;
    protected $ruleModel;
    protected $logger;
    protected $collectionFactory;
    protected $stockHelper;
    protected $storeManager;
    protected $cartItemFactory;
    protected $productRepository;
    protected $cart;
    protected $appState;
    protected $scopeConfig;

    public function __construct(
        MagentoCheckoutModelSession $checkoutSession,
        MagentoQuoteModelQuoteItem $itemModel,
        MagentoSalesRuleModelRule $ruleModel,
        PsrLogLoggerInterface $logger,
        MagentoCatalogModelResourceModelProductCollectionFactory $collectionFactory,
        MagentoCatalogInventoryHelperStock $stockHelper,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoQuoteApiDataCartItemInterfaceFactory $cartItemFactory,
        MagentoCatalogModelProductRepository $productRepository,
        MagentoCheckoutModelCart $cart,
        MagentoFrameworkAppState $appState,
        MagentoFrameworkAppConfigScopeConfigInterface $scopeConfig
    ) {
        $this->checkoutSession = $checkoutSession;
        $this->itemModel = $itemModel;
        $this->ruleModel = $ruleModel;
        $this->logger = $logger;
        $this->collectionFactory = $collectionFactory;
        $this->stockHelper = $stockHelper;
        $this->storeManager = $storeManager;
        $this->cartItemFactory = $cartItemFactory;
        $this->productRepository = $productRepository;
        $this->cart = $cart;
        $this->appState = $appState;
        $this->scopeConfig = $scopeConfig;
    }

    /**
     * @param Observer $observer
     */
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        $quote = $observer->getEvent()->getQuote();
        if ($quote instanceof MagentoFrameworkModelAbstractModel) {

            $appliedRules = ();

            $quoteItems = $quote->getAllItems();

            if (count($quoteItems) == 0) {
                return;
            }

            if ($quote->getAppliedRuleIds()) {
                $appliedRules = explode(',', $quote->getAppliedRuleIds());
            }

            /**
            CASE-2,
            if rule ids exists,
            check count of each rule id,
            if found count greater than allowed samples,
            forcily remove extra free samples
            */
            if (count($appliedRules) > 0) {
                $allowedSamplesLimit = 0;
                $cartAddedsamples = 0;
                $associatedSamples = ();
                $removeExtraSamples = ();
                $mergedAssociatedSamples = ();
                $sampleSkuArray = ();
                $i=0;

                foreach ($appliedRules as $eachRule) {
                    $ruleModel = '';
                    $ruleModel = $this->ruleModel->load($eachRule);
                    if ($ruleModel->getIsActive()) {
                        if ($ruleModel->getAutoAddtocart() != 3) { //means free, normal, deluxe
                            $sampleSkuArray() = explode(',', $ruleModel->getAssociated());
                            $allowedSamplesLimit += (int)$ruleModel->getNumberItem();
                        } else { //means gift-regimen
                            if ($ruleModel->getPrepare()) {
                                $sampleSkuArray() = explode(',', $ruleModel->getPrepare());
                                $allowedSamplesLimit += (int)$ruleModel->getNumberItem();
                            }
                            if ($ruleModel->getCleanse()) {
                                $sampleSkuArray() = explode(',', $ruleModel->getCleanse());
                                $allowedSamplesLimit += (int)$ruleModel->getNumberItem();
                            }
                            if ($ruleModel->getTreat()) {
                                $sampleSkuArray() = explode(',', $ruleModel->getTreat());
                                $allowedSamplesLimit += (int)$ruleModel->getNumberItem();
                            }

                            if ($ruleModel->getFourth()) {
                                $sampleSkuArray() = explode(',', $ruleModel->getFourth());
                                $allowedSamplesLimit += (int)$ruleModel->getNumberItem();
                            }

                            if ($ruleModel->getFifth()) {
                                $sampleSkuArray() = explode(',', $ruleModel->getFifth());
                                $allowedSamplesLimit += (int)$ruleModel->getNumberItem();
                            }
                        }

                        if (is_array($sampleSkuArray)) {
                            foreach ($sampleSkuArray as $eachSample) {
                                if (is_array($eachSample)) {
                                    foreach ($eachSample as $eachSku) {
                                        if ($eachSku) {
                                            $associatedSamples() = trim($eachSku);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
        
                $mergedAssociatedSamples = array_map('strtoupper', $associatedSamples);
                $addedSampleSkus = ();

                try {
                    foreach ($quoteItems as $eachItem) {
                        if (ceil($eachItem->getPrice()) == (int)0 && $eachItem->getFreeSample()) {
                            if (in_array(strtoupper($eachItem->getSKU()), $mergedAssociatedSamples)) {
                                /**
                                important,
                                no risk for samples more than 1 qty,
                                forcily set qty 1 for free-samples
                                */
                                $eachItem->setQty(1);
                                /**
                                ends
                                */
                                $cartAddedsamples++;
                                
                                if (!$eachItem->getFreeSample() && ceil($eachItem->getPrice()) == (int)0) {
                                    $eachItem->setFreeSample(true);
                                }

                                if ($cartAddedsamples > $allowedSamplesLimit) {
                                    $removeExtraSamples() = $eachItem->getItemId();
                                }
                            } else { //means free-sample not found in any rule and must be deleted
                                $removeExtraSamples() = $eachItem->getItemId();
                            }
                            if (!in_array($eachItem->getSKU(), $addedSampleSkus)) {
                                $addedSampleSkus() = $eachItem->getSKU();
                            } else {
                                //make sure, no sample can be appeared twice in cart
                                $removeExtraSamples() = $eachItem->getItemId();
                            }
                        }
                    }
                                        
                    if ($this->appState->getAreaCode() != MagentoFrameworkAppArea::AREA_ADMINHTML) {
                        $flagDelete = false;
                        foreach ($quoteItems as $eachItem) {
                            if (in_array($eachItem->getItemId(), $removeExtraSamples) &&
                                $eachItem->getParentItemId()==null) {
                                    $itemId = $eachItem->getItemId();
                                    $quoteItem = $this->itemModel->load($itemId);
                                    $quoteItem->delete();
                                    $flagDelete = true;
                            }
                        }
                        if ($flagDelete == true) {
                            $this->cart->save();
                        }
                    }

                } catch (MagentoFrameworkExceptionLocalizedException $e) {
                    $this->logger->critical($e);
                } catch (Exception $e) {
                    $this->logger->critical($e);
                }
            } else {
                $flagDel = false;
                foreach ($quoteItems as $eachItem) {
                    if (ceil($eachItem->getPrice()) == (int)0 && $eachItem->getFreeSample()) {
                        $itemId = $eachItem->getItemId();
                        $quoteItem = $this->itemModel->load($itemId);
                        $quoteItem->delete();
                        $flagDel = true;
                    }
                }
                if ($flagDel == true) {
                    $this->cart->save();
                }
            }
            /**
            ends
            */
        }
    }
}

How do I update the minicart count when the free items are removed from the cart?

magento2 – How to redirect user to Cart page after “Add to Cart”?

I have made a custom .phtml file to show “Add to Cart” button where I call/use the .phtml file in a CMS page.

Below is my code:

<?php 
    $sku = $block->getData('product-sku');
    $objectManager = MagentoFrameworkAppObjectManager::getInstance(); 
    $productRepository = $objectManager->get('MagentoCatalogModelProductRepository');
    $product = $productRepository->get($sku);
    $productid = $product->getId();
    $listBlock = $objectManager->get('MagentoCatalogBlockProductListProduct');
    $addToCartUrl =  $listBlock->getAddToCartUrl($product);

    $postDataHelper = $this->helper('MagentoFrameworkDataHelperPostHelper');
    $postData = $postDataHelper->getPostData($block->getAddToCartUrl($product), ('product' => $productid));
?>
<strong><?= $block->escapeHtml(__('produtc sku')) ?></strong>
<?php echo $sku; ?><br>
<form data-role="tocart-form" action="<?php echo $addToCartUrl; ?>" method="post"> 
    <?php echo $block->getBlockHtml('formkey')?>
    <div class="btn">
        <button type="submit" title="Add to Cart" class="action tocart primary">
            <span>Add to Cart</span>
        </button>
    </div>   
</form>

Is there any way that using the above code, I redirect the user to the cart page too? I don’t want to do it through admin panel as that will apply to all “Add to Cart” buttons in the website. I just want it for this specific CMS page.

Thank you.

magento2 – How to add a discount or apply a cart rule programmatically to quote in checkout_submit_before observer Magento 2

I want to apply some discounts amounts to the the quote, the observer I’m using is checkout_submit_before. There I have the access to the quote and order objects.

How can I apply a cart rule or a custom discount amount to the quote?

$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$coupon('name') = 'group_product';
$coupon('desc') = 'Cart Rule for Grouped Products';
$coupon('start') = date('Y-m-d');
$coupon('end') = '';
$coupon('max_redemptions') = 1;
$coupon('discount_type') = 'by_fixed';
$coupon('discount_amount') = $discountAmount;
$coupon('flag_is_free_shipping') = 'no';
$coupon('redemptions') = 1;
$coupon('code') = $quote->getId();

$shoppingCartPriceRule = $objectManager->create('MagentoSalesRuleModelRule');
$shoppingCartPriceRule->setName($coupon('name'))
    ->setDescription($coupon('desc'))
    ->setUsesPerCustomer($coupon('max_redemptions'))
    ->setCustomerGroupIds(array('0', '1', '2', '3',))
    ->setIsActive(1)
    ->setSimpleAction($coupon('discount_type'))
    ->setDiscountAmount($coupon('discount_amount'))
    ->setDiscountQty(1)
    ->setTimesUsed($coupon('redemptions'))
    ->setWebsiteIds(array('1'))
    ->setCouponType(2)
    ->setCouponCode($coupon('code'))
    ->setIsAdvanced(true)
    ->setStopRulesProcessing(false)
    ->setDiscountStep(0)
    ->setUsesPerCoupon(NULL);
$shoppingCartPriceRule->save();
$quote->setCouponCode($coupon('code'));

currently, I’m trying code but got no luck, maybe do I have to change the observer?

Reload page after removing item from Mini cart in magento 2.3.3

Is there any way to reload the page completely, when we remove an item from mini cart.
https://prnt.sc/11i1x2g
After clicking on ok , i want to reload the page.

plugins – Easy Digital Downloads – Cart not working on AWS hosting

We have a site hosted on AWS. But, the Easy Digital Downloads cart is not working properly. Items added to cart disappears and the items are not removed as well. Also, there is no any cache plugin installed. There are only some basic plugins installed and there is no error on browser console.

Can someone hopefully shed some light on this?

Thank you.

woocommerce offtopic – WordPress Custom Cart

hello guys i have a created a wordpress site and i am using rest api to display the products n categories in my app

in that i have created a custom cart php file where i am getting the productid n name etc..

i want to add some additonal parameters when the product is added to cart, i saw extra product option plugin in wordpress so how can i integrate my custom cart to extra product option or how to add additional parameters to my cart so i can send the data when user clicks on add to cart in app.

how can i implement this n i m using _woocommerce_persistent_cart_1

below is my php code

<?php

/**
 * REST API Webhooks controller
 *
 * Handles requests to the /webhooks endpoint.
 *
 * @package Automattic/WooCommerce/RestApi
 * @since   2.6.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * REST API Webhooks controller class.
 *
 * @package Automattic/WooCommerce/RestApi
 * @extends WC_REST_Webhooks_V2_Controller
 */
class WC_REST_Webhooks_Controller extends WC_REST_Webhooks_V2_Controller {

    /**
     * Endpoint namespace.
     *
     * @var string
     */
    protected $namespace = 'wc/v3';

    /**
     * Get the default REST API version.
     *
     * @since  3.0.0
     * @return string
     */
    protected function get_default_api_version() {
        return 'wp_api_v3';
    }
    
    protected $rest_base = 'custom';

    function woocomm_add_to_cart($param) {

        global $wpdb;
        $user_id = $param('user_id');
        wp_set_current_user($user_id);

        $objProduct = new WC_Session_Handler();     
        $wc_session_data = $objProduct->get_session($user_id);
        
        // Get the persistent cart may be _woocommerce_persistent_cart can be in your case check in user_meta table
        $full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart_1', true);

        if ( defined( 'WC_ABSPATH' ) ) {
            // WC 3.6+ - Cart and other frontend functions are not included for REST requests.
            include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
            include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
            include_once WC_ABSPATH . 'includes/wc-template-hooks.php';
        }

        if ( null === WC()->session ) {
            $session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );

            WC()->session = new $session_class();
            WC()->session->init();
        }

        if ( null === WC()->customer ) {            
            WC()->customer = new WC_Customer( get_current_user_id(), true );
        }
        
        if ( null === WC()->cart ) {
            WC()->cart = new WC_Cart();

            // We need to force a refresh of the cart contents from session here (cart contents are normally refreshed on wp_loaded, which has already happened by this point).
            WC()->cart->get_cart();
        }
        
        // create new Cart Object
        $cartObj = WC()->cart;
        
        
        // Add old cart data to newly created cart object
        if($full_user_meta('cart')) {           
            foreach($full_user_meta('cart') as $sinle_user_meta) {              
                $cartObj->add_to_cart( $sinle_user_meta('product_id'), $sinle_user_meta('quantity'), $sinle_user_meta('variation_id')  );
            }
        }
    
        // Add product and quantities coming in request to the new cart object
        if($param('products')){
            WC()->cart->empty_cart();
            foreach($param('products') as $prod) {
                $cartObj->add_to_cart( $prod('product_id'), $prod('quantity'), $prod('variation_id')  );                
            }
        }
        
        $updatedCart = ();
        foreach($cartObj->cart_contents as $key => $val) {
            unset($val('data'));
            $updatedCart($key) = $val;
        }

        // If there is a current session cart, overwrite it with the new cart
        if($wc_session_data) {
            $wc_session_data('cart') = serialize($updatedCart);
            $serializedObj = maybe_serialize($wc_session_data);


            $table_name = 'wp_woocommerce_sessions';

            // Update the wp_session table with updated cart data
            $sql ="UPDATE $table_name SET session_value= '".$serializedObj."' WHERE  session_key = '".$user_id."'";

            // Execute the query
            $rez = $wpdb->query($sql);
        }
    
        
        // Overwrite the persistent cart with the new cart data
        $full_user_meta('cart') = $updatedCart;

        
        $productsInCart = ();
        foreach($cartObj->cart_contents as $cart_item) {                            
             $product =  $cart_item('variation_id') == 0 ? wc_get_product( $cart_item('product_id') ) : wc_get_product( $cart_item('variation_id') );
             $image_id  = $product->get_image_id();
             $image_url = wp_get_attachment_image_url( $image_id, 'full' );
             $attributes =  $product->get_attributes();
 
             $productsInCart() = (object) (
                "product_id" => $cart_item('product_id'),
                "product_name" => wc_get_product( $cart_item('product_id') )->get_name(),
                "product_regular_price" => $product->get_regular_price(),
                "product_sale_price" => $product->get_sale_price(),
                "thumbnail" => $image_url,
                "qty" => $cart_item('quantity'),
                "attribute" => $attributes,             
                "line_subtotal" => $cart_item('line_subtotal'),
                "line_total" => $cart_item('line_total'),
                 "variation_id" => $cart_item('variation_id'),      
              );
        }
            
        
        update_user_meta(get_current_user_id(), '_woocommerce_persistent_cart_1', array('cart' => $updatedCart, ));         
        
        $response = (
            'status' => true,
            'data' =>  $full_user_meta('cart') != null ?  $productsInCart : ()          
        );

        return rest_ensure_response($response);
    }

    function woocomm_cart_list($param) {
        $user_id = $param('user_id');
        $objProduct = new WC_Session_Handler();

        $wc_session_data = $objProduct->get_session($user_id);

        // Get the persistent cart may be _woocommerce_persistent_cart can be in your case check in user_meta table
        $full_user_meta = get_user_meta($user_id,'_woocommerce_persistent_cart_1', true);
        
        $productsInCart = ();
        foreach($full_user_meta('cart') as $cart_item) {                            
             $product =  $cart_item('variation_id') == 0 ? wc_get_product( $cart_item('product_id') ) : wc_get_product( $cart_item('variation_id') );
             $image_id  = $product->get_image_id();
             $image_url = wp_get_attachment_image_url( $image_id, 'full' );
             $attributes =  $product->get_attributes();
 
             $productsInCart() = (object) (
                "product_id" => $cart_item('product_id'),
                "product_name" => wc_get_product( $cart_item('product_id') )->get_name(),
                "product_regular_price" => $product->get_regular_price(),
                "product_sale_price" => $product->get_sale_price(),
                "thumbnail" => $image_url,
                "qty" => $cart_item('quantity'),
                "attribute" => $attributes,             
                "line_subtotal" => $cart_item('line_subtotal') ?? 0,
                "line_total" => $cart_item('line_total') ?? 0,
                "variation_id" => $cart_item('variation_id'),               
              );
        }
                    
        $response = (
            'status' => true ,              
            'data' =>  $full_user_meta('cart') != null ?  $productsInCart : ()      
        );

        return rest_ensure_response($response);
    }
    
    public function register_routes() {
        register_rest_route(
            $this->namespace,
            '/addtocart',
            array(
                'methods' => 'POST',
                'callback' => array( $this, 'woocomm_add_to_cart' ),
            )
        );
        
        register_rest_route(
            $this->namespace,
            '/cart',
            array(
                'methods' => 'GET',
                'callback' => array( $this, 'woocomm_cart_list' ),
            )
        );
    }
}