php - Sum total products kcal , Protein and other attributes Woocommerce

425

I'm using a plugin for my wordpress website that is using JQuery to display products.

As you can see in the image below it is showing the product name, price and in the grey below it the attributes which are Kcal and protein amount

I'm trying to make it sum the total Kcal and protein of all products in cart and show above the total price

enter image description here

I tried adding this code in the functions.php file but didn't work

  function myprefix_cart_extra_info() {
  $volume = 0;

  // Iterating though each item in cart
  $cart_items = WC()->cart->get_cart();
  foreach( $cart_items as $cart_item ){
    $item_id = $cart_item['product_id'];
    $terms = get_the_terms( $item_id , 'kcal');
      foreach($terms as $key => $term)
        if(!empty($term->name)) $volume += $term->name;
    }

  echo '<div >';
  echo '<p >' . __('Total Kkcal', 'woocommerce');
  echo ' ' . $volume . ' ' . 'kcal';
  echo '</p>';
  echo '</div>';
}
280

Answer

Solution:

Add this script to your website:

var currentTotalKals;
var totalKalsContainer = $('#total-cals-sum');
var totalProteinSum = $('#total-protein-sum');
var totalFettSum = $('#total-fett-sum');
var totalKolhydrateSum = $('#total-kolhydrate-sum');


/* get number from string */
function getNumValue(string) {
    string = string.toString();
    var stringNum = string.replace(/\D/g, "");
    stringNum = stringNum == "" ? 0 : stringNum;
    return parseInt(stringNum);
}

/* get existing total kals */
function getExistingTotalKals() {
    let tempKals = totalKalsContainer.text().trim();
    tempKals = tempKals == "" ? 0 : tempKals;
    tempKals = parseInt(tempKals);  
    return tempKals;    
}

/* get existing total */
function getExistingTotal(element) {
    let tempExisting = element.text().trim();
    tempExisting = tempExisting == "" ? 0 : tempExisting;
    tempExisting = parseInt(tempExisting);
    return tempExisting;
}

/* update dom with new value */
function updateDOMWithNewValue(element, value) {
    element.text(value);
}

/* decide whether left text has protein or kolhydrates */
function getValueAndType(string, type) {
    console.log(string);
    let valueAndType = [];
    //let divider = (type == "onAdding") ? "</option>" : "<br>";
    let divider = "br";

    let parts = string.split(divider);
    console.log(parts);
    parts.pop();

    parts.forEach(part => {

        let numValue = getNumValue(part);
        valueAndType.push(getValueType(part,numValue));
    });
    return valueAndType;
}

/* decide whether left text has protein or kolhydrates */
function getValueType(string, numValue) {
  if(string.includes("Protein")) {
    return {
      element : totalProteinSum,
      type: "Protein",
      value : numValue  
    }
  }
  else if(string.includes("Fett")) {
    return {
      element: totalFettSum,
      type: 'Fett',
      value : numValue
    }
  }
  else if(string.includes("Kolhydrater")) {
      return {
      element: totalKolhydrateSum,
      type: 'Kolhydrater',
      value : numValue
    }
  }
}

then on adding the product :

            currentTotalKals = getExistingTotalKals();
            /* add current product kals to total */
            currentTotalKals+= getNumValue(product.right_text);
            /* update dom with new total kal value*/
            updateDOMWithNewValue(totalKalsContainer,currentTotalKals);


            /* decide whether its protien or kolhydrater */
            let otherDetails = getValueAndType(product.left_text,'onAdding');
            console.log(otherDetails);
            otherDetails.forEach(detail => {
                // get existing total
                let currentTotal = getExistingTotal(detail.element);
                // add current value to total
                currentTotal+= getNumValue(detail.value);
                //update dom
                updateDOMWithNewValue(detail.element, currentTotal);
            });

and on removing the product:

        /** custom logic starts here .... */
        currentTotalKals = getExistingTotalKals();

        /* finding the item to be removed */
        let itemToBeRemoved = $('.added_' + item_id);
        /* find the amount of cals it had */
        let kalToBeRemoved = $('.cal-values', itemToBeRemoved).text();

        let leftSidebarDetails = $('.sidebar_left_text', itemToBeRemoved).html();

        if(leftSidebarDetails !== undefined) {
        let detailsType = getValueAndType(leftSidebarDetails,'onRemoval');  
            detailsType.forEach(detail => {
                let currentTotal = getExistingTotal(detail.element);
                currentTotal-= detail.value;
                currentTotal = currentTotal == 0 ? "" : currentTotal;
                updateDOMWithNewValue(detail.element,currentTotal);
            });             
        }


        /* calculate new total */
        currentTotalKals-= getNumValue(kalToBeRemoved);
        currentTotalKals = currentTotalKals == 0 ? "" : currentTotalKals;
        /* update DOM */
        updateDOMWithNewValue(totalKalsContainer, currentTotalKals);

People are also looking for solutions to the problem: Automatically execute a PHP script

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.