I have a magento script that runs from command line that needs to get a price quote based off of the weight of an item. (Feel free to improve any of this script) I don't want to adjust the weight in the database but I want to adjust it for when I get the shipping quote.

setlocale(LC_MONETARY, 'en_US');
ini_set('display_errors',true); Mage::setIsDeveloperMode(true);

$userModel = Mage::getModel('admin/user');


$mask = " %7s | %-30s | %-15s | %-30s \n";
// Need to figure out how to temporarily adjust a products weight without saving it.
function calculate_weight($weight){
        // If under 1lb 1.5 x $weight
        // If 1lb to 5lbs 1.25 x $weight
        // If 5lb+ 1.2 x $weight
        if ($weight < 1) { return $weight * 1.5;}
        elseif ($weight < 5) { return $weight * 1.25;}
        else return $weight * 1.2;
function getShippingEstimate($productId,$productQty,$countryId,$postcode ) {
    global $mask, $aprox;
    $quote = Mage::getModel('sales/quote')->setStoreId(Mage::app()->getStore('default')->getId());
    //Check if is SKU or Number.
    if (is_numeric($productId)){

        $_product = Mage::getModel('catalog/product')->load($productId);

    } else

        $model = Mage::getModel('catalog/product');
        $product_id = $model->getIdBySku($productId);
        $_product = $model->load($product_id);
    $cost = $_product->getCost();
    $name = $_product->getName();
    $minPriceWithShipping = $_product->getMinPriceWithShipping();
    $shippingPrice = $_product->getShippingPrice();
    $aprox = $shippingPrice+($cost*$productQty);
    printf($mask, number_format((float)$cost, 2, '.',''), $name, number_format((float)$minPriceWithShipping, 2, '.',''),number_format((float)$aprox, 2, '.','') . '  QTY:'.$productQty);

    $weight = $_product->getWeight();

    if ($weight <= 0) { echo $weight; return 9999.99; }
    // php getShipping.php ons6467 1 57.87   1.6000 Weight

    echo $weight." Weight \n";
    $weight = calculate_weight($weight);
    echo $weight." New Weight \n";
    //echo $_product->setWeight($weight);    <---  This breaks th code    I just want to temporarily adjust the weight for calculations
    // Don't want to save Weight

    $quote->addProduct($_product, $productQty);

    $_rates = $quote->getShippingAddress()->getShippingRatesCollection();
    $shippingRates = array();
    foreach ($_rates as $_rate):
        if($_rate->getPrice() > 0) {
            $shippingRates[] =  array("Title" => $_rate->getMethodTitle(), "Price" => $_rate->getPrice(), "Carrier" => $_rate->getCarrier(), "Carrier Title" => $_rate->getCarrierTitle());
    return $shippingRates;


// Place this at the very top of script
$start = microtime(TRUE);

// product id, quantity, country, postcode

$c = (isset($argv[2])) ? $argv[2] : 1;

$rates = getShippingEstimate($argv[1] , $c , "US","04652");// Farthest continental USA Zip code from warehouse that I could find.
function sortr($a, $b) {
    return $a['Price'] - $b["Price"];

usort($rates, "sortr");

//$fst = array_shift($rates);

// only min-width of cells is set

foreach($rates as $rate){
    printf($mask, number_format((float)$rate['Price'], 2, '.','') , $rate['Title'],strtoupper($rate['Carrier']) ,'');
if (isset($argv[3])) { 
    $v= $argv[3]-$aprox;
    echo "$".number_format((float)$v, 2, '.','') . " Estimated Profit. \n"; 

$finish = microtime(TRUE);

// Subtract the start time from the end time to get our difference in seconds
$totaltime = $finish - $start;

echo "This script took ".$totaltime." seconds to run \n";
  • Do we know the shipping cost formula? My idea is NOT no change the product weight before, but modify the shipping rates by percentage or table values based on the weight difference. So create some shipping rule formula based on weight adjustment.
    – Amasty
    Jul 23 '14 at 10:11
  • It uses UPS/FedEx/USPS Api to get the shipping. How would I go about doing your idea with that?
    – Brad
    Jul 23 '14 at 15:19
  • I see the issue. There was a chance it is table rate or transparent formula.
    – Amasty
    Jul 23 '14 at 15:33
  • What do you mean by "This breaks th code" on line $_product->setWeight($weight);?
    – Marius
    Jul 31 '14 at 7:03
  • it causes an error to be thrown when you don't call $_product->save();
    – Brad
    Jul 31 '14 at 7:09

Try to use Mage_Shipping_Model_Shipping::collectRates method.

It takes as a parameter shipping request Mage_Shipping_Model_Rate_Request $request

And the request contains total products weight. So you can modify it using your own logic per each product and then sum up.

No need to save anything in the database.



0) remove weight adjustments from the script

1) add Mage::register('my-commad-line-flag',1); in the script beginning.

2) create custom module, that rewrites just one class:

class Amasty_Example_Model_Shipping_Shipping extends Mage_Shipping_Model_Shipping
    public function collectRates(Mage_Shipping_Model_Rate_Request $request)
        // apply the rates only when called from the custom script
        if (Mage::registry('my-commad-line-flag')){
            // re-calculate total package weight
            $total = 0;
            foreach($request->getAllItems() as $item){
                // use your function here
                $total += my_custom_weight_adjustment($item->getWeight()) * $item->getQty();



        return $this;
  • Do you know where any demo code is to use this. I'm lost trying to figure this out. Thanks
    – Brad
    Jul 25 '14 at 20:37
  • Works like a charm!
    – Brad
    Aug 1 '14 at 23:03
  • Nice! Glad to help ;) Does it mean i get the bounty?
    – Amasty
    Aug 2 '14 at 4:05
  • I thought I gave you the bounty.. :P Yes you earned it! Thanks
    – Brad
    Aug 2 '14 at 6:41

Not Completely sure but we had a similar issue, what we did was created a database field like "NewWeight" and then you can save the temporary weight in there, setNewWeight("10"); that is the easiest and safest way to go around. But if you dont want to use database , as Amasty suggested you can use collectRates,

I dont have full working code with me but it will be something like

public function collectRates(Mage_Shipping_Model_Rate_Request $request)
    $result = Mage::getModel('shipping/rate_result');
    return $result;

protected function _getXYZShippingRate()
    $rate = Mage::getModel('shipping/rate_result_method');

    /*put all of your weight cal logic over here and just get the price and cost so you                   dont have to bother with saving the weight of the product"

        $rate->setPrice(100); //whatever the price you have calcuated
        $rate->setCost(99); //whatevr the cost

    return $rate;




I think by far the easiest method of achieving the desired functionality is as follows:

in your getShippingEstimate method, round line 58:

$weight = calculate_weight($weight);
$old_weight = $_product->getWeight();
$_product->save(); //temporarily adjust weight

$quote->addProduct($_product, $productQty);
$_product->save(); //revert to actual weight

It's not the most elegant of solutions, but it is a solution nonetheless. Let me know if this is what you're trying to achieve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.