Get Random SKU Product Number - magento

I have the following code:
$sku = $id;
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
It works by specfing the SKU id, I want to be able to get random SKU product number and use it so
$sku = random product number from database

I used the following script to generate a random sku from the collection. You can use it to suit your requirement also.
//Geting a random sku from collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$randomSku = $collection->setPage(1, 1)->getFirstItem()->getSKU();
In your case your code should look like.......
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$_product = $collection->setPage(1, 1)->getFirstItem()->load();
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();

Something like that should work fine ;)
$collection = Mage::getResourceModel(‘catalog/product_collection’);
Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
$collection->getSelect()->order(‘rand()’);
$collection->addStoreFilter();
$collection->setPage(1, 1);
$_product = $collection->getFirstItem();

Below code I used in project and its working fine for me :
<?php
// get Random prdocut list
$collection = Mage::getResourceModel(‘catalog/product_collection’);
Mage::getModel(‘catalog/layer’)->prepareProductCollection($collection);
$collection->getSelect()->order(‘rand()’);
$collection->addStoreFilter();
$numProducts = $this->getNumProducts() ? $this->getNumProducts() : 2;
$collection->setPage(1, $numProducts);
foreach($collection as $product){
echo $product->getName();
}
?>

Related

How can i update my products?

I want to update from my script the meta title, the meta description and the meta keywords for all of my products.
The meta title = the name of the product
The meta description = the short description of the product
The meta keywords is the meta keywords i've put from the category of the product.
I can loop and get the informations i want to make the update (except the meta keywords of the description) and after how i can make the update inside the loop ?
Thanks
<?php require_once 'app/Mage.php';
umask(0);
set_time_limit(0); // ignore php timeout
ignore_user_abort(true); // keep on going even if user pulls the plug*
while(ob_get_level())ob_end_clean(); // remove output buffers
ob_implicit_flush(true); // output stuff directly
//error_reporting(E_ALL);
/* not Mage::run(); */
Mage::app('default');
// get product collection (All product)
$storeId = Mage::app()->getStore()->getId();
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG);
$_productCollection = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addAttributeToFilter('visibility', $visibility)
->setStoreId($storeId)
->addStoreFilter($storeId);
foreach ($_productCollection as $pro) { // loop each product
$meta_title = $pro['meta_title'];
$meta_description = $pro['meta_description'];
$name = $pro['name'];
$short_description = $pro['short_description'];
// I want to update the meta_title, meta_description, meta_keywords
// meta_description = short_description
// meta_title = name
// meta_keywords = meta keywords from the category of the product
}
?>
You can easy set keyword and description by using standard setters.
Inside foreach loop just use :
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$product->setMetaTitle('Product Title')
->setMetaKeyword('Product keywords')
->setMetaDescription('Product Description')
->save();
endforeach;
Try this,
foreach ($_productCollection as $pro):
$product = Mage::getModel('catalog/product')->load($pro->getId());
$cats = $product->getCategoryIds();
$meta_keys = '';
foreach ($cats as $category_id) {
$_cat = Mage::getModel('catalog/category')->load($category_id) ;
if($_cat->getMetaKeywords())
$meta_keys .= $_cat->getMetaKeywords().', ';
}
$product->setMetaTitle($pro->getName())
->setMetaKeyword($meta_keys)
->setMetaDescription($pro->getShortDescription())
->save();
endforeach;

magento get product using proudct id

I am trying to get feature product of magento, I am getting all product ids properly in each variables, but its not working inside the loop and shows repeated product.
here is my code
$storeId = Mage::app()->getStore()->getId();
$categoryId = $this->getRequest()->getParam('id', false);
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('catalog_read');
$categoryProductTable = $resource->getTableName('catalog/category_product');
//$productEntityIntTable = $resource->getTableName('catalog/product_entity_int'); // doesn't work :(
$productEntityIntTable = (string)Mage::getConfig()->getTablePrefix() . 'catalog_product_entity_int';
$eavAttributeTable = $resource->getTableName('eav/attribute');
$select = $read->select()
->from(array('cp'=>$categoryProductTable))
->join(array('pei'=>$productEntityIntTable), 'pei.entity_id=cp.product_id', array())
->joinNatural(array('ea'=>$eavAttributeTable))
->where('pei.value=1')
->where('ea.attribute_code="featured"');
$_product = $read->fetchAll($select);
$total_product= count($_product);
when i print_r($_product) it shows multiple id of product which are features so its correct
but inside for loop when i try to get product name using id it shows repeated Product names,here is the code
$obj = Mage::getModel('catalog/product');
for($cp=0;$cp <= $total_product; $cp++):
$_product= $obj->load($_product[$cp]['product_id']);
echo $_product->getName();
endfor;
Try this
for($cp=0;$cp <= $total_product; $cp++):
$obj = Mage::getModel('catalog/product');
$_productnew= $obj->load($_product[$cp]['product_id']);
echo $_productnew->getName();
endfor;
Put $obj inside for loop like below,
for($cp=0;$cp <= $total_product; $cp++):
$obj = Mage::getModel('catalog/product');
$_product= $obj->load($_product[$cp]['product_id']);
echo $_product->getName();
endfor;

get qty of products in an order with several products

Hi i would like to know how to get the qty_ordered of a specific product in an order with several products.
i have tried these
$orders = Mage::getModel('sales/order')->getCollection()->
addAttributeToSelect('shipping_description')->
addAttributeToSelect('increment_id')->
addAttributeToSelect('base_grand_total')->
addAttributeToSelect('total_qty_ordered')->
addAttributeToSelect('shipping_address_id')->
addAttributeToSelect('billing_address_id')->
addAttributeToSelect('created_at')->
addAttributeToSelect('shipping_incl_tax')->
addAttributeToFilter('status', 'pending');
but addAttributeToSelect('total_qty_ordered')-> which total? which product?
"total_qty_ordered" give total no orders qty of all product in an order
If,you want item qty of product then
you can try
<?php $order_id = 2314; //use your own order id
$order = Mage::getModel("sales/order")->load($order_id); //load order by order id
$ordered_items = $order->getAllItems();
foreach($ordered_items as $item){ //item detail
echo $item->getItemId();
//product id
echo $item->getSku();
echo $item->getQtyOrdered();
//ordered qty of item
echo $item->getName();
// etc.
} ?>
for me it worked like this:
<?php
$_order = $this->getOrder(); //call the order
$order_qty = floor($_order->getData('total_qty_ordered')); //get qty of all items rounded to full number (without 3.0000 or so)
echo $order_qty;
?>
used it on template/sales/order/totals.phtml
You can Try this also:-
$orderCollection = Mage::getModel('sales/order');
$order_data = $orderCollection->getAllVisibleItems();
foreach ($order_data as $key) {
$id = $key->getProductId();
$orderItems = Mage::getResourceModel('sales/order_item_collection')
->addAttributeToFilter('product_id', $id);
foreach ($orderItems as $key ) {
echo $number_of_prod = $key->getQtyOrdered();
}
}

Check If Product Exists

I have some php code which I use SKU for it:
$sku = $id
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
What I would like to add to this code if $sku is wrong (Not found in database with $_product line) to be able to change it manually for example if the $sku is not existent change it to $sku = "909010";
Thank you for the help
function get_product($sku){
$product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
if (!$product){
$new_sku = '909010'; // If Real SKU doesn`t exsist, change to '909010'
$product=Mage::getModel('catalog/product')->loadByAttribute('sku',$new_sku);
}
return $product;
}
var_dump(get_product('your-sku')); // Real Sku
$sku = $id
$_product=Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
if(!is_object($_product) || !$_product->getId()){
//do your stuff here
}
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();
$sku = $id
$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku); //Get Product by ID (ASIN)
$_product = !empty($product) ? $product : Mage::getModel('catalog/product')->loadByAttribute('sku','YOUR-ERROR-SKU');
$qtyStock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty(); //if in stock
$_prodcats = $_product->getCategoryIds();

Magento - Product Collection with the current user's Wishlist

Within a Magento php Controller, how can I get a Product Collection containing the products listed in the logged in user's (ie current user's) Wishlist.
I am getting the Wishlist using:
$wishList = Mage::getModel('wishlist/wishlist')->loadByCustomer(Mage::getSingleton('customer/session')->getCustomer());
and this contains the correct number of items.
But I would like to get a Product Collection. I have tried:
$productCollection = $wishList->getProductCollection();
and
$productCollection = $wishList->getProductCollection()->addAttributeToSelect('id')->load();
but the Product Collection I get has a length of 0.
How do I get the Product Collection?
You can use the getWishlistItemCollection (see link for more details) off the wishlist helper to return a collection of items, you then need to get the product from the item.
I have been using the following code to create an associative array of the products, which I then use to determine if a product I am displaying in the list page is in the wishlist...hopefully this will help:
public function getWishList() {
$_itemCollection = Mage::helper('wishlist')->getWishlistItemCollection();
$_itemsInWishList = array();
foreach ($_itemCollection as $_item) {
$_product = $_item->getProduct();
$_itemsInWishList[$_product->getId()] = $_item;
}
return $_itemsInWishList;
}
Try this with product all details like name, images etc...
<?php
$customer = Mage::getSingleton('customer/session')->getCustomer();
if($customer->getId())
{
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
echo $item->getName()."</br>";
echo $item->getId()."</br>";
echo $item->getPrice()."</br>";
echo $item->getQty()."</br>";
$item = Mage::getModel('catalog/product')->setStoreId($item->getStoreId())->load($item->getProductId());
if ($item->getId()) :
?>
<img src="<?php echo Mage::helper('catalog/image')->init($item, 'small_image')->resize(113, 113); ?>" width="113" height="113" />
<?php endif; } } ?>
$customer = Mage::getSingleton('customer/session')->getCustomer();
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customer, true);
$wishListItemCollection = $wishlist->getItemCollection();
foreach ($wishListItemCollection as $item)
{
// do things
}

Resources