Magento random product - magento

Hi I use a script for showing random products on my homepage, but it doesnt show me price. Where is a problem?
http://magentoabid.blogspot.sk/2012/06/display-random-products-from-category.html

Not sure why that isn't working, but if you want you try some other solutions
http://dx3webs.com/front/2010/10/how-to-create-a-random-featured-product-list-on-home-page-in-magento/
Update the code above
Replace the first ~15 lines with:
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getModel('catalog/layer')->prepareProductCollection($collection);
$collection->getSelect()->Limit($this->getNumProducts())->order('rand()');
$collection->addStoreFilter();
$collection->addCategoryFilter($category);
//print_r($collection);
Replace :
<?php for ($i=0; $i < $number_of_products; $i++): ?>
with :
<?php foreach($collection as $product) : ?> //need to end foreach with <?php endforeach; ?>
Replace things like this :
$displayed_products[$random_products[$i]]->getName();
With :
$product->getName();
(find and replace "$displayed_products[$random_products[$i]]" with "$product")

Related

Magento - how to filter categories in phtml

I have been working on the maga menu. I got the collection in phtml like:
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
Now I have to add the filter to show specific categories. Like I have an array(1,2,3,4) of categories that i want to show. so how can I apply filter to this Helper.
Any one have any suggestion please answer.
Thanks.
The first answer is correct but it's not efficient as it consumes unnecessary database round trips. #Karan's code issues a query to the database for every id. Just imagine if the number of category ids to be filtered were 50 or above.
My example would be this:
<?php
$catIds = array(1,2,3,4);
$catCollection = Mage::getModel('catalog/category')->getCollection()->addAttributeToFilter('id', $catIds)->addAttributeToFilter('is_active',1);
foreach($catCollection as $category){
echo $category->getName()." ";
}
This will reduce the database roundtrip to just one.
use this code
<?php $catids[]=array(1,2,3,4);
foreach($catids as $id):
$_category = Mage::getModel('catalog/category')->load($id);
if($_category->getIsActive()):
echo $_category->getName();
endif;
endforeach;
?>
and don't forget to link my answer if it was helpful

Subcategory list with Magento Flat Catalog

I'm using the code below to get a list of categories on the same level as the current page (by listing the subcategories of this category's parent). It works great when Flat Categories are off. Once I enable Flat Categories, the H2 works correctly, but the list changes to display the root's subcategories instead of this page's parent's subcategories. What am I doing wrong, and why does it act this way?
<?php
$_category = $this->getCurrentCategory();
$parentCategoryId = $_category->getParentId();
$collection = Mage::getModel('catalog/category')->getCategories($parentCategoryId);
$helper = Mage::helper('catalog/category');
$parentCategory = Mage::getModel('catalog/category')->load($parentCategoryId);
?>
<h2><?php echo $parentCategory->getName(); ?></h2>
<ul>
<?php foreach ($collection as $cat):?>
<?php if($_category->getIsActive()): ?>
<li <?php
if ($cat->getId() == $_category->getId()) {
echo 'class="current"';
}
?>>
<?php echo $cat->getName();?>
</li>
<?php endif; ?>
<?php endforeach;?>
</ul>
Yes, I've flushed the cache and indexes.
I don't completely know why ->getCategories($id) is not "flat-safe", but using Stefan's suggestion helped me find an alternate method for this instead.
My new lines at top look like this:
$_category = $this->getCurrentCategory();
$parentCategoryId = $_category->getParentId();
$helper = Mage::helper('catalog/category');
$parentCategory = Mage::getModel('catalog/category')->load($parentCategoryId);
$collection = $parentCategory->getChildrenCategories();
... which works regardless of 'flat catalog' on or off.

How to make second root category navigation in magento?

Other than the normal navigation I get when I add subcategories to the main root category, I want to be able to make a new root category, assign subcategories to it and have it display as a separate menu.
Is this possible?
May this can help you :Link 1Link 2
To retrieve another root category
<?php
echo '<pre>';
$id=9;
$catagory_model = Mage::getModel('catalog/category');
$categories = $catagory_model->load($id); // where $id will be the known category id
if(!empty($categories))
{
echo 'category name->'.$categories->getName(); //get category name
echo '<br>';
echo 'category image url->'.$categories->getImageUrl(); //get category image url
echo '<br>';
echo 'category url path->'.$categories->getUrlPath(); //get category url path
echo '<br>';
}
?>
now $id=9; is my new root category id.
To retrieve sub categories of these new root category ($id=9;) below is the following reference code.Customize it according to your requirements.
<?php $helper = $this->helper('catalog/category') ?>
<?php $categories = $this->getStoreCategories() ?>
<?php foreach($categories as $category): ?>
<?php $subcategories = $category->getChildren() ?>
<?php foreach($subcategories as $subcategory): ?>
<?php $subsubcategories = $subcategory->getChildren() ?>
<?php foreach($subsubcategories as $subsubcategory): ?>
<?php endforeach; ?><!-- end foreach subsubcategories -->
<?php endforeach; ?><!-- end foreach subcategories -->
<?php endforeach; ?><!-- end foreach categories -->
In an ideal world you would have found the answer by now, but in case you didn't I modified Nikhil's answer to work for me to basically do what you describe, minus any convenience at all...
$id=9;
$catagory_model = Mage::getModel('catalog/category');
$categories = $catagory_model->load($id);
if(!empty($categories))
{
$cats = explode(",", $categories->getChildren());
foreach($cats AS $c)
{
$cat = $catagory_model->load(trim($c));
echo ''.$cat->getName().'';
}
}
I'm just pasting what I used. The reality is you will have to build the html to make this do whatever you want it to do. If you have subcategories within your loop, you will have to run another fetch in the foreach part.
I am not familiar with magento enough to know what methods you can run on the $cat object. I did a print_r($cat) to examine the object and made a lucky guess that getUrlKey would be available.
Magento... pfft! you'd think ebay would have higher standards than this.

Google Affiliate Integration with Magento 1.7

So maybe you guys can help me out here, im trying to integrate googles tracking pixel for their Google Affiliate program. Im using the following code from here http://www.studio1909.com/2009/10/16/google-affiliate-network-conversion-tracking-pixel-magento-ecommerce/ However, after going back and forth with google they aren't so excited about the way the code from the above link is printing out the data when it comes to configurable products.
<!--Start Google Affiliate Integration-->
<?php
$lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getSingleton('sales/order');
$order->load($lastOrderId);
$order = Mage::getModel('sales/order')->load($lastOrderId);
foreach ($order->getAllItems() as $item) {
$productArray[] = array(
"product_sku" => $item->getSku(),
"product_magento_id" => $item->getProductId(),
"product_name" => $item->getName(),
"product_qty" => $item->getQtyOrdered(),
"product_price" => $item->getPrice(),
"product_discount_amount" => $item->getDiscountAmount(),
"product_row_price" => $item->getPrice() - $item->getDiscountAmount(),
);
};
?>
<?php
$_totalData = $order->getData();
$_subtotal = $_totalData['subtotal'];
$_orderID = $_totalData['increment_id'];
?>
<img src="https://clickserve.cc-dt.com/link/
order?vid=KVENDORID&oid=<?php echo "$_orderID"; ?>&amt=<?php echo "$_subtotal"?>&prdsku=<?php foreach ($productArray as $key) {echo $key['product_sku']."^";};
?>&prdnm=<?php foreach ($productArray as $key) {echo $key['product_name']."^";};
?>&prdqn=<?php foreach ($productArray as $key) {echo $key['product_qty']."^";};
?>&prdpr=<?php foreach ($productArray as $key) {echo $key['product_price']."^";};
?>&prcatid=<?php foreach ($productArray as $key) {echo "your-product^";};
?>" width=1 height=1>
<!--End Google Affiliate Integration-->
This is the end result
<!--Start Google Affiliate Integration-->
<img src="https://gan.doubleclick.net/gan_conversion?advid=MYID&event_type=transaction&oid=10000XXXX&amt=19.0000&fxsrc=USD&prdsku=DVT2756CH CHAR M^DVT2756CH CHAR M^&prdnm=DaVinci 1952 In Charcoal T-Shirt^DaVinci 1952 In Charcoal T-Shirt^&prdqn=1.0000^1.0000^&prdpr=19.0000^0.0000^&prcatid=4425^4427^" width=1 height=1>
<!--End Google Affiliate Integration-->
So the question is there a way to edit the code above so it just echoes the main configurable product without the simple product.
Thanks!
One good place to look at this is the template for displaying the order items:
app/design/frontend/base/default/template/sales/order/items.phtml
and the code for the loop is:
<?php $_items = $_order->getItemsCollection(); ?>
<?php $_index = 0; ?>
<?php $_count = $_items->count(); ?>
<?php foreach ($_items as $_item): ?>
<?php if ($_item->getParentItem()) continue; ?>
So this can be a good way to get what you need.

Sorting categories in Magento according to the position in admin

I would like to know how to sort this list of categories (I followed this tutorial here http://www.devinrolsen.com/magento-custom-category-listing-block/) in magento by position in the admin panel? Currently it is sorted by id
<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildren();
$catIds = explode(',',$cats);
?>
<ul>
<?php foreach($catIds as $catId): ?>
<li>
<?php
$category = Mage::getModel('catalog/category')->load($catId);
echo '<a href="' . $category->getUrl() . '">';
echo $category->getName() . '</a>';
?>
</li>
<?php endforeach; ?>
</ul>
You're making way too much work for yourself trying to deal with IDs and stuff. The following is already sorted by position as standard.
<?php
$cats = Mage::getModel('catalog/category')->load(3)->getChildrenCategories();
?>
<ul>
<?php foreach($cats as $category): ?>
<li>
<?php echo $category->getName() ?>
</li>
<?php endforeach; ?>
</ul>
If you want to sort the categories by the position created in adminhtml you can then, since catalog/category is an instance of Mage_Catalog_Model_Resource_Category_Collection, make a query where you specify what you want to select, filter and/or sort.
The case here is getting categories from catalog_category_entity select only the name, filtering after the id and sort the query on the position.
<?php
$subcategories = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('name')
->addFieldToFilter('parent_id', $categoryId)
->addAttributeToSort('position', ASC);
?>
This is what I did:
$allCategories = Mage::getModel('catalog/category');
$CategoriesTree = $allCategories->getTreeModel()->load();
$categoriesIds =
$CategoriesTree->getCollection()->addAttributeToSort('position', 'asc')->getAllIds();
after to retrieve the categories:
$categoryChildren = array();
if ($categoriesIds) {
foreach ($categoriesIds as $categoryId){
$category = Mage::getModel('catalog/category')->load($categoryId);
$categoryChildren[] = $category;
}
}
and then:
// Sort by position
function comparePosition($a, $b) {
if ($a->position == $b->position)
return 0;
return ($a->position > $b->position) ? 1 : -1;
}
usort($categoryChildren, 'comparePosition');
Inverting the return (1 and -1) would obviously change the order.
It worked just fine for me.
Hope it helps someone.
I strongly suggest to lok here first http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-8-varien-data-collections and also other articles in knowledge base are a must read for any magento dev.
<?php
$cats = Mage::getModel('catalog/category')->addAttributeToSort('yourfield', 'desc')->getCollection()->getChildren();
$catIds = explode(',',$cats);
?>
<?php
$model_category = Mage::getModel('catalog/category')->load($_category->getEntityId());
$sub_categories = $model_category->getCollection();
$sub_categories -> addAttributeToSelect('url_key')
-> addAttributeToSelect('name')
-> addAttributeToFilter('is_active',1)
-> addIdFilter($model_category->getChildren())
-> setOrder('position', 'ASC')
-> load();
?>
<?php foreach($sub_categories->getData() as $each_subcat): ?>
<?php $model_subcat = Mage::getModel('catalog/category')->load($each_subcat['entity_id']); ?>
<?php endforeach; ?>

Resources