Opencart Display Stock Quantity On Category Page - php

We have a used furniture website running Opencart 1.5.2.1 and want to display the quantity value on the category page to allow people to know how many are in stock without clicking on the item as well as a product code/model as we have a large quantity of items on our website but some may only have a low quantity but they would have to manually check each item to find out the quantity.
I'm sure that its simple to do but my attempts have not worked. I don't need to have it so the customer can add to basket, just display the stock value.
This is because we usually never get the same item twice so the stock value is very important.
The first answer given does not help my problem, the website is http://www.mayfairfurnitureclearance.co.uk/index.php?route=product/category&path=112_157 that link takes you straight to a category where I have been attempting this, at this minute it is displaying only a number 2 or a number 1 in some categories by using the code from the first answer and changing it to get results. Currently only displays on the "Grid" display mode as not many people use it at this time.

You need to do bit modification in controller/catalog/category.php
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'description' => utf8_substr(strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8')), 0, 100) . '..',
'price' => $price,
'special' => $special,
'tax' => $tax,
'rating' => $result['rating'],
'reviews' => sprintf($this->language->get('text_reviews'), (int)$result['reviews']),
'href' => $this->url->link('product/product', 'path=' . $this->request->get['path'] . '&product_id=' . $result['product_id'])
);
you need to forward Stock value to above product array and need to echo at category page e.g
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'stock' => $result['quantity']
in view/catalog/category.tpl
<div><?php echo $product['stock']; ?></div>
it will display like value of quantity in category page

here is another option to hide an item in category page if the stock quantity is zero.
go to controller/product/product.php
search this line:
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
and underneath 'name' => $result ['name'], add this code:
'stock' => $result['quantity'],
to become:
$this->data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'stock' => $result['quantity'],
this will get the stock indicated in opencart.
After you add the above code, go to view/theme/default/template/product/product.tpl
search: foreach ($products as $product) {
and add something like this:
<?php
foreach ($products as $product) {
if($product['stock'] > 0) { ?>
the above code will check if the corresponding stock of each product has a quantity or not. Don't forget to close the bracket.
Happy Coding!!!

Related

How to loop through a list of products and categories on PHP

<?
$categoriesID = array("popular","old");
$product => array (
Product 1
'categoryID' => $categoriesID[1],
'Name' => 'Product One',
Product 2
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
Product 3
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
Product 4
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
);
How can I loop through this to reflect that product 1 belongs to category 1, product 2 belongs to category 2, product 3 belongs to category 2 and so on?
I tried the following but no luck..
foreach($product as $key => $pro){
var_dump($categoriesID[$key]);
}
I would really appreciated any suggestions or how what i'm doing wrong.The goal is to insert the relationship into a database table where in order to insert a product a category_id is required.
Your arrays are not written correctly. You got a multi dimensional array here (arrays inside of an array). Read this to understand how they are written and how you can work with them: http://php.net/manual/en/language.types.array.php
If your categories are numeric you should also consider to use numeric values: 1 instead of '1' inside of the $categoriesID array or depending on the database auto casting capability you will get issues inserting strings as decimals.
Here is your given code modified as working example. Ive changed the var_dump output for better readability of the result.
Ive also changed the array indexes you have used since arrays start at 0. If you need the numbers still to start at 1 you could add some nonsense value at the beginning of the array or subtract 1 when accessing the array. Keep in mind that this is an quick & dirty solution to the given problem.
Nevertheless as Patrick Q said you should consider some introduction to PHP.
<?php
$categoriesID = array('1','2');
$product = array (
array(
'categoryID' => $categoriesID[0],
'Name' => 'Product One',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
)
);
foreach($product as $key => $value){
echo var_export($value, true) . '<br>';
}
You could further edit Mariusz's answer to do something like this:
foreach($product as $item){
echo $item['Name'].' - '.$item['categoryID'].'<br>';
}
This would give you easy access to both product name and category ID.

How to update the quantity of all items in the cart with respect to database?

I am doing a shopping cart using code-igniter. While I can do the add cart functions, I'm somewhat confused with how to update them with regards to database. All I want is when I change the item quantity in the cart and click update ,both the cart and database must be updated for that particular item.I tried to do it but couldn't get it.Can someone please enlighten me what to do?
controller code
$this->load->model('user_m');
$result['query'] = $this->user_m->get($id); // inserts coresponing item
foreach ($result['query'] as $row)
$id = $row->pid;
$qty = $a;
$quan=$row->quantity;
$price = $row->pprice;
$name = $row->pname;
$q=$quan-$a; // for remainig stock i.e total qty-user qty
$data = array(
'id' => $id,
'qty' => $qty,
'price' => $price,
'name' => $name,
'stock' =>$q
);
$this->cart->insert($data);
$this->load->model('user_m');
$result['qry'] = $this->user_m->up_cart($id,$q);
redirect($_SERVER['HTTP_REFERER']);
}
just tell me how to update pls!
when ever you add any product in cart, it will generate an uniq row ID and that will be unique for each and every product and hence you need to update quantity by that row ID
$data = array(
'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
'qty' => 3
);
$this->cart->update($data);
// Or a multi-dimensional array
$data = array(
array(
'rowid' => 'b99ccdf16028f015540f341130b6d8ec',
'qty' => 3
),
array(
'rowid' => 'xw82g9q3r495893iajdh473990rikw23',
'qty' => 4
),
array(
'rowid' => 'fh4kdkkkaoe30njgoe92rkdkkobec333',
'qty' => 2
)
);
$this->cart->update($data);
Now you want to know about how you will get row id.
$cart=$this->cart->contents();
it will return whole array of cart and when you listing it on webpage, please associate row id with quantity text box to update that particular product.
please check following url:
https://ellislab.com/codeigniter/user-guide/libraries/cart.html

WooCommerce Changing Simple Product to Variable and Vice Versa, but how to get new variations to show on the frontend?

I am creating a plugin that ties into the Runit System for showing onhand products in WooCommerce. This requires changing products via a Cron job that will update them, from Simple Products to Variable Products and vice versa depending on the quantity of stock and the variations of these products, which change. I have working code, that updates these products in the backend, showing the correct variations, however, it does not update on the front end. The new variations, even when editing Variable Products, do not show on the front end when viewing the actual Product itself. I still see the old variations in there. How to update the variations to use the new variations automatically, instead of having to hit the Update button in the backend Administration when editing the Product?
Is there some sort of function that needs to be called for updating the Variations in WooCommerce that I'm not aware of? I am using the array like this and serializing it before updating the meta_value for the meta_key _product_attributes in wp_postmeta table, like so:
function ProcessBasicProperties(Array $properties)
{
$return = array();
$position = 0;
if (!empty($properties))
{
if (!empty($properties['siz']))
{
++$position;
$size = !is_array($properties['siz']) ? array($properties['siz']) : array_unique($properties['siz']);
$return['size'] = array(
'name' => 'Size',
'value' => count($size) > 1 ? implode(' | ', $size) : $size[0],
'is_visible' => count($size) > 1 ? 0 : 1,
'is_variation' => count($size) > 1 ? 1 : 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['ext']))
{
++$position;
$extension = !is_array($properties['ext']) ? array($properties['ext']) : array_unique($properties['ext']);
$return['extension'] = array(
'name' => 'Extension',
'value' => count($extension) > 1 ? implode(' | ', $extension) : $extension[0],
'is_visible' => count($extension) > 1 ? 0 : 1,
'is_variation' => count($extension) > 1 ? 1 : 0,
'is_taxonomy' => 0,
'position' => $position
);
}
// styles do not get added to attributes for variable products, instead, with variable products, the style goes into the overall sku of the product (General Properties)
// So, in short, variable products should not have this key set.
if (!empty($properties['style']))
{
++$position;
$return['style'] = array(
'name' => 'Style',
'value' => htmlspecialchars($properties['style'], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['color']))
{
++$position;
$colors = !is_array($properties['color']) ? array($properties['color']) : array_unique($properties['color']);
$return['color'] = array(
'name' => 'Color',
'value' => count($colors) > 1 ? htmlspecialchars(implode(' | ', $colors), ENT_QUOTES) : htmlspecialchars($colors[0], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['gender']))
{
++$position;
$return['gender'] = array(
'name' => 'Gender',
'value' => htmlspecialchars($properties['gender'], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
if (!empty($properties['season']))
{
++$position;
$return['season'] = array(
'name' => 'Season',
'value' => htmlspecialchars($properties['season'], ENT_QUOTES),
'is_visible' => 1,
'is_variation' => 0,
'is_taxonomy' => 0,
'position' => $position
);
}
}
return $return;
}
This is a function that returns the proper array that get serialized and inputted into the wp_postmeta table for the meta_value where meta_key = _product_attributes. Each variation also has a meta_key of attribute_size and meta_key of attribute_extension where the meta_value equals the value of that specific variation as required within the wp_postmeta table for that posts variation ID.
I'm at a loss, trying to update the variations of a Variable Product, or when Converting a Simple Product to a Variable Product, that needs to be updated. It shows up fine in the backend admin panel of the product, but when going to the actual product page, it still shows the OLD product variations. The only way to show the new one's is to go into the backend admin panel of the product and hit the Update button, which than shows all of the new variations. But how to do this programmatically? I thought this was possible? Must be something I'm overlooking here? Perhaps there are terms somewhere that need updating?
Functions that I have tried, that failed to update the product with the new variations, s for small = variation id 181342 and l for large = variation id 181343 from ID column of of wp_posts table or post_id column of the wp_postmeta table for that Variation:
wp_set_object_terms(181342, 's', 'size');
wp_set_object_terms(181343, 'l', 'size');
and
do_action( 'woocommerce_create_product_variation', 181342 );
do_action( 'woocommerce_create_product_variation', 181343 );
None of these update the product as a variation that shows on the front end. It still shows ONLY the old variations on the front end. How to get the size s and l showing on the front end?
Figured it out... looks like you have to update the wp_options table using set_transient... Here's what I did and it nipped it in the bud:
$transients = array(
'name' => array(
'wc_product_total_stock_' . $product_id,
'wc_product_children_ids_' . $product_id
),
'values' => array(
$total_stock,
$allVariationIDs
),
'filters' => array(
'woocommerce_stock_amount'
)
);
// Set it up so that the variations show in the front end also...
foreach($transients['name'] as $k => $transient_name)
{
set_transient($transient_name, $transients['values'][$k],YEAR_IN_SECONDS);
if (isset($transients['filters'][$k]))
apply_filters($transients['filters'][$k], $transients['values'][$k]);
}
$product_id = the actual products ID value.
$allVariationIDs = an array of all ID values of the variations within the wp_posts table. $total_stock is the new stock of the product, calculating in all variation stock levels.
Hope this helps someone else to update their variations on the front end, after setting up all wp_posts and wp_postmeta table rows for your products and variations.
Along with updating product attributes, you will also have to update the product variations from the database.
For example, while deleting the product variations, you will have to remove it from the wp_posts table
You can refer this link for more details
Woocommerce - Cannot delete a product variation

the best way to store quantity in $_SESSION

I have the following function to add products to shopping cart:
function AddToCart($pid)
{
$_SESSION['products'][]['product_id'] = $pid;
}
What is the best way to store product quantity to the same array with the product id, since the array after the ['products'] generates automatically I'm confused how can I assign quantity there? Thank you for your help:)
Why not store all of the information you need at the same time? Here is an excerpt from my own cart:
// add item to cart
$_SESSION['cart'][] = array('product_id' => $product_id,
'cat_id' => $cat_id,
'title' => $title,
'default_img' => $default_img,
'price' => $valid_product['base_price'],
'weight' => $valid_product['weight'],
'length' => $valid_product['length'],
'width' => $valid_product['width'],
'height' => $valid_product['height'],
'surcharge' => $surcharge,
'quantity' => $quantity,
'prop_selection' => $prop_selection,
'po_id' => $po_id,
'stock' => $stock,
'shipper_id' => $valid_product['shipper_id']);
If I understand the question correctly, when AddToCart() is called for a $pid that is already in the array, do you just want it to increment a quantity property for that product? Seems to me you just will need to use an associative array for $_SESSION['products'] instead of a numerically indexed array like you are now:
function AddToCart($pid, $quantity=1) {
if(is_array($_SESSION['products']) && array_key_exists($pid, $_SESSION['products'])) {
$_SESSION['products'][$pid]['quantity'] += $quantity;
} else {
$_SESSION['products'][$pid] = array(
'product_id' => $pid,
'quantity' => $quantity
);
}
}

Get value from custom category attribute

I am trying to get the value from a custom category attribute in Magento. The attribute is a select field and is been made with the install script below:
$this->startSetup();
$this->addAttribute('catalog_category', 'category_categorycolor', array(
'group' => 'General Information',
'input' => 'select',
'type' => 'varchar',
'label' => 'Categorie kleur',
'backend' => '',
'visible' => 1,
'required' => 0,
'user_defined' => 1,
'option' => array (
'value' => array('yellow' => array('Geel'),
'purple' => array('Paars'),
'blue' => array('Blauw'),
'red' => array('Rood'),
'orange' => array('Oranje'),
'green' => array('Groen'),
'darkblue' => array('Donkerblauw'),
'lightgreen' => array('Lichtgroen'),
)
),
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));
$this->endSetup();
Unfortunately only getting numbers and not text value. I use this line to retrieve the value:
<?php $_category_categorycolor = $_category->getData('category_categorycolor'); if($_category_categorycolor): ?> <?php echo $_category_categorycolor; ?> <?php endif; ?>
Can someone help me?
Something like this:
$category_id = '10';
$attribute_code = 'category_categorycolor';
$category = Mage::getModel('catalog/category')->load($category_id);
echo $category->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($category);
The sollution is pretty messy (the only one I know of).
$opt = array(); // will contain all options in a $key => $value manner
$attribute = Mage::getSingleton('eav/config')->getAttribute('catalog_category', 'category_categorycolor');
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
foreach ($options as $o) {
$opt[$o['value']] = $o['label'];
}
}
$categoryColorId = $_category->getData('category_categorycolor');
$categoryColorLabel = $opt[$categoryColorId];
// if you have problems, do a Zend_Debug::dump($opt);
// - it should contain an array of all the options you added
Didn't test it out, let me know if it works or not.
PS: can't reply to your comment, not sure why. What does $opt contain ?
The numbers you are getting back are the id's of each value in the dropdown. You have to load the dropdown values too.
See the following page. It helped me understand this.
http://www.sharpdotinc.com/mdost/2009/04/06/magento-getting-product-attributes-values-and-labels/

Categories