How to get all woocommerce shipping packages in a custom template - php

I need to let customer edit their pending payment order. By default, woocommerce only allow change the payment method. So, I have created a custom template for this feature.
The problem now I encountered is I can't get the shipping packages in the template.
Here is the code that I adapted from the wc_cart_totals_shipping_html() :
$packages = WC()->shipping->get_packages();
print_r($packages);
foreach ( $packages as $i => $package ) {
//blah blah blah
}
The print_r($packages) give me the null array. But on the checkout page, it's working fine.
Any idea why? Or, get the shipping packages by other method?

Please try this -
global $woocommerce;
$customerZipCode = 75098;
$zipResultArr = csd_check_zip_and_state($customerZipCode);
$bh_packages = $woocommerce->cart->get_shipping_packages();
$bh_packages[0]['destination']['state'] = $zipResultArr['state'];
$bh_packages[0]['destination']['postcode'] = $customerZipCode ;
$bh_packages[0]['destination']['city'] = $zipResultArr['city'];
$bh_packages[0]['destination']['address'] = '';
$bh_packages[0]['destination']['address_2'] = '';
//Calculate costs for passed packages
$bh_shipping_methods = array();
foreach( $bh_packages as $bh_package_key => $bh_package ) {
$bh_shipping_methods[$bh_package_key] = $woocommerce->shipping->calculate_shipping_for_package($bh_package, $bh_package_key);
}
$shippingArr = $bh_shipping_methods[0]['rates'];
if(!empty($shippingArr)) {
$response = array();
foreach ($shippingArr as $value) {
$shipping['label'] = $value->label;
$shipping['cost'] = $value->cost;
$response['shipping'][] = $shipping;
}
}
// This is your shipping
print_r($response);

Related

Prestashop: How to get virtual product in the cart for use in Address.php?

In Prestashop CMS, address1 is only required if there is a virtual product in the cart.
How can this be achieved? Does anybody have the solution for this?
$context = Context::getContext();
$cart = $context->cart;
$is_virtual = $cart->isVirtualCart();
Works perfectly. Example:
if (in_array('address1', $arr) && $is_virtual) {
$this->def['fields']['address1']['required'] = 0;
} else if (in_array('address1', $arr)) {
$this->def['fields']['address1']['required'] = 1;
$this->fieldsRequired[] = 'address1';
} else {
$this->def['fields']['address1']['required'] = 0;
}

Programmatically stop decreasing stock qty while placing an order in magento and increaging qty when order state is Compleate

In Magento 1.9.0.1 by default, it decreases stock qty while placing an order. I want to stop decreasing stock qty while placing an order for the purpose of fake order. And I also want the functionality of increasing stock qty while order state is complete, not pending, not processing. How to do it programmatically or by setting up in Admin panel. If any one knows about it, please reply back.
Thank You
Ankan
Just simply open your admin panel, go to System->Configuration->Catalog Tab->Inventory Then click on Stack Option and change Decrease Stock When Order is Placed to NO.
Thanks,
Lovekesh
In Admin panel, System->Configuration->Catalog Tab->Inventory Then click on Stack Option and change Decrease Stock When Order is Placed to NO. So that it stops the stock qty increasing.In Model/Automatically/Complete/Order/Observer.php page, class Webspidy_Customoption_Model_Automatically_Complete_Order_Observer
{ public function __construct(){}
public function automaticallycompleteorder($observer)
{
//Mage::log('Ankan');
$order = $observer->getEvent()->getOrder();
/$orders = Mage::getModel('sales/order_invoice')->getCollection()
->addAttributeToFilter('order_id', array('eq'=>$order->getId()));/
/*if ((int)$orders->count() !== 0) {
return $this;
}*/
//Mage::log($orderstate);
//if($order->getState() == 'complete'){
if(($order->getState() == 'processing') || ($order->getState() == 'pending_payment')){
if($order->hasInvoices()){
//Mage::log($orderstate);
//Mage::log('Ankan');
//Mage::log($order->getData());
//====== Order Details ================
$orderNumber = $order->getIncrementId(); //Mage::log($orderNumber);
$orderDet = Mage::getModel('sales/order')->load($orderNumber, 'increment_id');
//Mage::log($orderDet->getData());
$orderItems = $orderDet->getItemsCollection()
->addAttributeToSelect('*')
->load();
foreach($orderItems as $orderItem){
$productId = $orderItem->getProductId();
$productOptionSku = $orderItem->getSku();
$productQty = $orderItem->getQtyOrdered();
$product = Mage::getModel('catalog/product')->load($productId);
$sku = $product->getSku();
$centralqty = $product->getStockItem()->getQty();
$values = array();
foreach ($product->getOptions() as $o) {
$p = $o->getValues();
}
foreach($p as $v)
{
$optionSku = $v->getSku();
$optionItem = $v->getQty();
//Mage::log($optionItem);
//Mage::log($productOptionSku.".....".$sku."-".$optionSku.".....".$optionItem);
if($productOptionSku == ($sku."-".$optionSku)){
if($centralqty >= ($optionItem*(int)$productQty)){
//$stockQty = (($centralqty-($optionItem*(int)$productQty))+$productQty);
$stockQty = ($centralqty-($optionItem*(int)$productQty));
}
}
}
$product->save();
//Mage::log($stockQty);
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
//$stockItem = Mage::getModel('cataloginventory/stock_item')->load($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('qty', $stockQty);//(integer)$XMLproduct->QtyInStock
$stockItem->setData('manage_stock',1);
$stockItem->save();
}
}
//======== End ======
}
}
}
And in etc/config.xml,
<global><events>
<sales_order_save_after><observers>
<webspidy_customoption_automatically_complete_order_observer>
<type>singleton</type> <class>Webspidy_Customoption_Model_Automatically_Complete_Order_Observer</class>
<method>automaticallycompleteorder</method>
</webspidy_customoption_automatically_complete_order_observer>
</observers></sales_order_save_after></events></global> After a long process, I have got a success by creating Observer in my custom module.
I am using Magento 1.9
I have tried with the following code. it's OK But i have another smart code
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemId = $stockItem->getId();
$stockItem->setData('qty', $stockQty);
$stockItem->setData('manage_stock',1);
$stockItem->save();
My code is following:-
Mage::getModel('cataloginventory/stock')->backItemQty($productId,$new_qty);

woocommerce - billing order fields change with different countries

I'm working with woocommerce to build a webshop. I've customized the order of the billing address fields. The problem is, some countries still display a different order. How can I force the custom order for all countries?
EDIT:
<?php
/*
* Modifing the order of form fields.
* More information here: http://www.trottyzone.com/change-order-of-woocommerce-fields-on-checkout-page/
*/
add_filter('woocommerce_checkout_fields','reorder_woo_fields');
function reorder_woo_fields($fields) {
//move these around in the order you'd like
$fields2['billing']['billing_first_name'] = $fields['billing']['billing_first_name'];
$fields2['billing']['billing_last_name'] = $fields['billing']['billing_last_name'];
$fields2['billing']['billing_email'] = $fields['billing']['billing_email'];
$fields2['billing']['billing_company'] = $fields['billing']['billing_company'];
$fields2['billing']['billing_address_1'] = $fields['billing']['billing_address_1'];
$fields2['billing']['billing_postcode'] = $fields['billing']['billing_postcode'];
$fields2['billing']['billing_city'] = $fields['billing']['billing_city'];
$fields2['billing']['billing_country'] = $fields['billing']['billing_country'];
$fields2['billing']['billing_state'] = $fields['billing']['billing_state'];
$fields2['billing']['billing_phone'] = $fields['billing']['billing_phone'];
$fields2['shipping']['shipping_first_name'] = $fields['shipping']['shipping_first_name'];
$fields2['shipping']['shipping_last_name'] = $fields['shipping']['shipping_last_name'];
$fields2['shipping']['shipping_email'] = $fields['shipping']['shipping_email'];
$fields2['shipping']['shipping_company'] = $fields['shipping']['shipping_company'];
$fields2['shipping']['shipping_address_1'] = $fields['shipping']['shipping_address_1'];
$fields2['shipping']['shipping_postcode'] = $fields['shipping']['shipping_postcode'];
$fields2['shipping']['shipping_city'] = $fields['shipping']['shipping_city'];
$fields2['shipping']['shipping_country'] = $fields['shipping']['shipping_country'];
$fields2['shipping']['shipping_state'] = $fields['shipping']['shipping_state'];
$fields2['shipping']['shipping_phone'] = $fields['shipping']['shipping_phone'];
//just copying these keeps the standard order
$fields2['account'] = $fields['account'];
$fields2['order'] = $fields['order'];
return $fields2;
}
?>
Check the woocommerce class-wc-countries.php file there it sets the locale. I think your problem can solved by the following code
add_filter( 'woocommerce_get_country_locale', 'use_only_default_locale' );
function use_only_default_locale( $locale ) {
return array();
}
EDIT:
Try this code
add_filter( 'woocommerce_default_address_fields', 'my_default_address_fields' );
function my_default_address_fields( $fields ) {
//move these around in the order you'd like
$fields2['first_name'] = $fields['first_name'];
$fields2['last_name'] = $fields['last_name'];
$fields2['email'] = $fields['email'];
$fields2['company'] = $fields['company'];
$fields2['address_1'] = $fields['address_1'];
$fields2['postcode'] = $fields['postcode'];
$fields2['city'] = $fields['city'];
$fields2['city']['label'] = 'City';
$fields2['city']['placeholder'] = 'City';
$fields2['country'] = $fields['country'];
$fields2['state'] = $fields['state'];
$fields2['phone'] = $fields['phone'];
return $fields2;
}
comment out add_filter('woocommerce_checkout_fields','reorder_woo_fields');
You need to change the field classes a bit to fill properly.
By using the woocommerce_checkout_fields filter you have full controll of the checkout fields.
// Hook in
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
// Our hooked in function - $fields is passed via the filter!
function custom_override_checkout_fields( $fields ) {
//Minipulate the `$fields` vaiable and return it
$fields['order']['order_comments']['placeholder'] = 'My new placeholder';
return $fields;
}
See the docs for more information: http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters

Google Checkout XML invalid value

I'm using a plugin called http://www.jigoshop.com with Wordpress (both the latest versions) and I'm having problems with their Google Checkout gateway.
I've tried their support but yet to get a response.
I'm getting the following errors when trying to order something:
Error parsing XML; message from parser is: Invalid value for attribute
unit-price in shopping-cart.items.item-2.unit-price: Required field
must not be blank
In the Google merchant console this translates to:
"XML that we recieved"
_type=checkout-shopping-cart&shopping-cart.merchant-private-data=273&checkout-flow-support.merchant-checkout-flow-support.continue-shopping-url=http%3A%2F%2Fwww.carolinemontagu.com%2Fv2%2Fevents%2Fcheckout%2Fthanks%2F&checkout-flow-support.merchant-checkout-flow-support.edit-cart-url=http%3A%2F%2Fwww.carolinemontagu.com%2Fv2%2Fevents%2Forder%2F&shopping-cart.items.item-1.item-name=Leadership+Success%3A+Early+bird+%26%238211%3B+19th+Oct&shopping-cart.items.item-1.item-description=&shopping-cart.items.item-1.unit-price=205.83&shopping-cart.items.item-1.unit-price.currency=GBP&shopping-cart.items.item-1.quantity=1&shopping-cart.items.item-1.merchant-item-id=211&shopping-cart.items.item-2.item-name=Shipping&shopping-cart.items.item-2.item-description=&shopping-cart.items.item-2.unit-price=&shopping-cart.items.item-2.unit-price.currency=GBP&shopping-cart.items.item-2.quantity=1&shopping-cart.items.item-2.merchant-item-id=
"XML that we sent"
_type=error&error-message=Error+parsing+XML%3B+message+from+parser+is%3A+Invalid+value+for+attribute+unit-price+in+shopping-cart.items.item-2.unit-price%3A+Required+field+must+not+be+blank&serial-number=3f096700-bb6f-4e28-8740-f6ffa0d09aeb
I've had a look through their code and can find this that corresponds to shopping-cart.items.item-2.unit-price:
private function formatOrder(jigoshop_order $order) {
$result = array(
'_type' => 'checkout-shopping-cart',
'shopping-cart.merchant-private-data' => $order->id,
'checkout-flow-support.merchant-checkout-flow-support.continue-shopping-url' => get_permalink(get_option('jigoshop_thanks_page_id')),
'checkout-flow-support.merchant-checkout-flow-support.edit-cart-url' => get_permalink(get_option('jigoshop_cart_page_id')),
//shipping-taxed
);
$i = 1;
foreach($order->items as $item) {
$prefix = "shopping-cart.items.item-$i.";//shopping-cart.items.item-1.item-name
$result[$prefix.'item-name'] = $item['name'];
$result[$prefix.'item-description'] = '';
$result[$prefix.'unit-price'] = $item['cost'];
$result[$prefix.'unit-price.currency'] = get_option('jigoshop_currency');
$result[$prefix.'quantity'] = $item['qty'];
$result[$prefix.'merchant-item-id'] = $item['id'];
$i++;
}
$prefix = "shopping-cart.items.item-$i.";
$result[$prefix.'item-name'] = __('Shipping', 'jigoshop');
$result[$prefix.'item-description'] = '';
$result[$prefix.'unit-price'] = $order->order_shipping;
$result[$prefix.'unit-price.currency'] = get_option('jigoshop_currency');
$result[$prefix.'quantity'] = 1;
$result[$prefix.'merchant-item-id'] = $order->shipping_method;
return $result;
}
Can anyone help with this problem? I'm really stuck with a deadline looming fast!
If you added only one item to the shopping cart, then based on the code provided, item-2 is the shipping cost.
Make sure your $order->order_shipping is initialized correctly.

Magento Configurable Product working but not showing until re-saved

I am currently learning how to create configurable product for Magento. Its all working fine, the product was successfully imported using my codes including its associated products. The problem is the product does not show up in front-end. I have to manually go to the back-end, edit the product and save it. Take note I do not have to change anything, I just need to open it, and save. Only then it will show up in front-end. Any idea why is that?
define('MAGENTO', dirname(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
require_once 'FeedMag.php';
$myFeed = new FeedMag();
Mage::app();
// test data
$sku = "TESTSKU2";
$inventory = "10";
$stockData['qty'] = $inventory;
$stockData['is_in_stock'] = 1;
$simple['Description'] = 'Configurable Product 1';
$simple['ShortDescription'] = 'Short Description';
$simple['LongDescription'] = 'Long Description';
$simple['BrandCode'] = 'Nike';
$attr['color'] = 'Blue';
$attr['size'] = 1;
$price = 11;
// get attribute id
foreach($attr AS $key=>$value) {
$attr_ids[] = $myFeed->attributeValueExists($key, $value);
}
$new = false;
echo "<pre>";
try {
// get product id from SKU
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
// load product if id exist or create a new one
if($id && $id > 0) {
$product = Mage::getModel('catalog/product')->load($id);
}
else {
$product = Mage::getModel('catalog/product')->setSku($sku);
$new = true;
}
// set it to configurable
$product->setTypeId('configurable');
// get attributes' id
$usingAttributeIds = $new_array = array();
foreach( $attr as $key=>$value ) {
$attribute = $product -> getResource() -> getAttribute( $key );
if ( $product -> getTypeInstance() -> canUseAttribute( $attribute ) ) {
if ( $new ) { // fix for duplicating attributes error
$usingAttributeIds[] = $attribute -> getAttributeId();
}
}
}
// if we have attributes' ID, set it to the product
if ( !empty( $usingAttributeIds ) ) {
$product -> getTypeInstance() -> setUsedProductAttributeIds( $usingAttributeIds );
$attributes_array = $product->getTypeInstance()->getConfigurableAttributesAsArray();
foreach($attributes_array as $key => $attribute_value) {
$attributes_array[$key]['label'] = $attribute_value['frontend_label'];
}
$product -> setConfigurableAttributesData($attributes_array);
$product -> setCanSaveConfigurableAttributes( true );
$product -> setCanSaveCustomOptions( true );
}
// set product data
$product->setStoreId(0)
->setAttributeSetId(4)
->setStockData($stockData)
->setPrice($price)
->setName($simple['Description'])
->setShortDescription($simple['ShortDescription'])
->setDescription($simple['LongDescription'])
->setCategoryIds(array(3))
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setBrand($simple['BrandCode'])
->setStatus(1)
->setTaxClassId(2) //Taxable goods
->save();
// get previous children if any
$associated = Mage::getModel('catalog/product_type_configurable')
->getChildrenIds($product->getId());
// add new simple product to configurable product
$associated[0][] = Mage::getModel('catalog/product')->getIdBySku('SIMPLE1');
// add all simple product to configurable product
Mage::getResourceModel('catalog/product_type_configurable')
->saveProducts($product->getId(), array_unique($associated[0]));
}
catch (Mage_Core_Exception $e) {
echo $e->getMessage();
}
catch (Exception $e) {
echo $e;
}
echo "</pre>";
FeedMag is a custom class made by my colleague. There's a lot of method in there but for this purpose I'll be using just one; attributeValueExists to check if said attribute exists and if it does, its ID will be returned.
Simple product already exists so I just need to use it (SIMPLE1).
Its an issue with the indices when importing. You must be missing a field in the export sheet that is required to associate the items and the store. The reason it works when you save is because its rebuilding the table indices which is filling in that missing data.

Categories