Trying to get str_replace working in custom Magento code - php

Here is my code:
<?php
$_rtl = Mage::getStoreConfig('custom_menu/general/rtl') + 0;
$_categories = $this->getStoreCategories();
if (is_object($_categories)) $_categories = $this->getStoreCategories()->getNodes();
?>
<div class="nav-container">
<div style="z-index:999;position:relative;top:-8px;left:979px;cursor:pointer;"><img src="<?php echo $this->getSkinUrl('images/Truck-Prince-text.png'); ?>" height="91" width="123" style="position:absolute;" onclick="location.href='<?php echo Mage::getUrl('checkout/cart'); ?>'"></div>
<div id="custommenu" class="<?php echo $_rtl ? ' rtl' : ''; ?>">
<?php if ($this->showHomeLink()) : ?>
<div class="menu">
<div class="parentMenu menu0">
<a href="<?php echo $this->getUrl('') ?>">
<span><?php echo $this->__('Home'); ?></span>
</a>
</div>
</div>
<?php endif ?>
<?php foreach ($_categories as $_category): ?>
<?php echo $this->drawCustomMenuItem($_category) ?>
<?php endforeach ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('nav-links-after')->toHtml() ?>
<div class="clearBoth"></div>
</div>
</div>
What I want to do is something like this but I don't know how to insert this in without causing errors. I basically want to change the existing url with the string replaced urls..
<?php // We must replace URLs on the fly to use landing pages and not break subcat navigation
$_category = str_replace('wild-bird-feed-supplies.html', 'landing-wild-bird-feed-supplies', $_category);
$_category = str_replace('lawn-garden-supplies.html', 'landing-lawn-garden-supplies', $_category);
$_category = str_replace('pet-food-supplies.html', 'landing-pet-food-supplies', $_category);
$_category = str_replace('animal-feed-supplies.html', 'landing-animal-feed-supplies', $_category); ?>

I finally was able to get it :) Here is what I did...
<?php
$_rtl = Mage::getStoreConfig('custom_menu/general/rtl') + 0;
$_categories = $this->getStoreCategories();
if (is_object($_categories)) $_categories = $this->getStoreCategories()->getNodes();
?>
<div class="nav-container">
<div style="z-index:999;position:relative;top:-8px;left:979px;cursor:pointer;"><img src="<?php echo $this->getSkinUrl('images/Truck-Prince-text.png'); ?>" height="91" width="123" style="position:absolute;" onclick="location.href='<?php echo Mage::getUrl('checkout/cart'); ?>'"></div>
<div id="custommenu" class="<?php echo $_rtl ? ' rtl' : ''; ?>">
<?php if ($this->showHomeLink()) : ?>
<div class="menu">
<div class="parentMenu menu0">
<a href="<?php echo $this->getUrl('') ?>">
<span><?php echo $this->__('Home'); ?></span>
</a>
</div>
</div>
<?php endif ?>
<?php foreach ($_categories as $_category): ?>
<?php $_category = $this->drawCustomMenuItem($_category) ?>
<?php // We must replace URLs on the fly to use landing pages and not break subcat navigation
$_category = str_replace('wild-bird-feed-supplies.html', 'landing-wild-bird-feed-supplies', $_category);
$_category = str_replace('lawn-garden-supplies.html', 'landing-lawn-garden-supplies', $_category);
$_category = str_replace('pet-food-supplies.html', 'landing-pet-food-supplies', $_category);
$_category = str_replace('animal-feed-supplies.html', 'landing-animal-feed-supplies', $_category); ?>
<?php echo $_category; ?>
<?php endforeach ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('nav-links-after')->toHtml() ?>
<div class="clearBoth"></div>
</div>
</div>

Related

Show random product on homepage through phtml

I have a block being displayed on my homepage which shows a product, whose id we specify. The code on homepage (static block) looks like this:
{{block type="core/template" product_id="2559" template="catalog/product/one_product.phtml"}}
The one_product.phtml file contains this code:
<?php
$productId = $this->getProduct_id();
$product = Mage::getModel('catalog/product')->load($productId); //load product
?>
<div class="product">
<a href="<?php echo $product->getProductUrl() ?>" >
<img class="product-img" src="<?php echo $this->helper('catalog/image')->init($product, 'image'); ?>"alt="<?php echo $this->htmlEscape($product->getName()) ?>" />
</a>
</div>
<div class="product-detail">
<P><?php // echo $this->htmlEscape($product->getName()) ?>
<?php $prod_name = $this->htmlEscape($product->getName()); ?>
<?php
$count_str = strlen($prod_name);
if ($count_str < 40) {
echo $prod_name;
} else {
$offset = 0;
$length = 41;
$prod_name = html_entity_decode($prod_name);
echo htmlentities(mb_substr($prod_name,0,$length,'utf-8')). "...";;
}
?>
</P>
<!--?php $price = $product->getPrice() ; ?-->
<?php $_product = Mage::getModel('catalog/product')->load($product->getId());
$productBlock = $this->getLayout()->createBlock('catalog/product_price');
?>
<span>
<?php echo $productBlock->getPriceHtml($_product); ?>
<?php $tier_price = end($_product->getTierPrice());
if($tier_price !='0'){ ?>
<span>As Low As:</span>
<?php
echo " ₹ ".number_format( $tier_price['price']);
} ?>
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart"
onclick="setLocation('<?php echo Mage::helper('checkout/cart')->getAddUrl($product); ?>')">
</span>
</div>
So basically I want to show random products out of the ones I specify separated by commas. For eg: I specify in the static block product_id="2559,2661,2857,9293" and it should show any one of those 4 products randomly.
What is the way to do that?
Also any way to make it pull products from SKU also? Since we remember all the SKUs but we have to check each product ID everytime we change the product here.
Please excuse me if the question is too basic, I'm not a developer.
You can see it in action at www.giftzila.com
Thanks!
Create a new file called random-product.phtml at app/design/frontend/default/Your_Theme/template/catalog/random-product.phtml then add the following code in that file
<?php
$chosen_category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$_productCollection = $this->getLoadedProductCollection();
$number_of_products = $this->getNumProducts();
if (sizeof($_productCollection) < $number_of_products) {
$number_of_products = sizeof($_productCollection);
}
$displayed_products = array();
foreach ($_productCollection as $_product) {
$displayed_products[] = $_product;
}
$random_products = array();
if (sizeof($_productCollection) > 1) {
$random_products = array_rand($displayed_products, $number_of_products);
} else {
$random_products = array('0');
}
?>
<?php if(!$_productCollection->getSize()):?>
<div class="note-msg">
<?=$this->__('There are no products matching the selection.')?>
</div>
<?php else:?>
<div class="main-binder">
<div class="cms-box">
<div class="category-title">
<h2>Random Products</h2>
</div>
<div class="category-products">
<table id="products-grid-table" class="products-grid">
<?php
$k=0;
for ($i=0; $i < $number_of_products; $i++): ?>
<?php if ($k == 0) { ?>
<tr class="first odd">
<?php } if($k==3) { $k=0; ?>
</tr><tr class="first odd even">
<?php } ?>
<td id="td_<?php echo ($k+1); ?>" <?php if($k==3){ ?>class="last"<? } ?> >
<div class="cms-box">
<div id="cont_<?php echo ($k+1); ?>">
<div class="product-name-block">
<?php
$pname=$this->htmlEscape($displayed_products[$random_products[$i]]->getName());
?>
<h3 class="product-name">
<a href="<?php echo $displayed_products[$random_products[$i]]->getProductUrl()?>" title="<?php echo $pname; ?>">
<?php if(strlen($pname) > 28) {echo substr($pname,0,25)."...";}else {echo $pname;}?>
</a></h3>
</div>
<div class="image-box">
<a class="product-image" href="<?php echo $displayed_products[$random_products[$i]]->getProductUrl()?>"> <img src="<?php echo $this->helper('catalog/image')->init($displayed_products[$random_products[$i]], 'small_image')->resize(140);?>" alt="<?php echo $this->htmlEscape($displayed_products[$random_products[$i]]->getName())?>" title="<?php echo $this->htmlEscape($displayed_products[$random_products[$i]]->getName())?>"/> </a>
</div>
<div class="cms-price-box" style=" text-align:center;">
<span class="regular-price" id="product-price-37">
<span class="price" ><?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->
getCurrentCurrencyCode())->getSymbol().$displayed_products[$random_products[$i]]->getPrice(); ?></span>
</span>
</div>
<div class="button-row" style="text-align:center;">
<button onclick="setLocation('<?php echo $displayed_products[$random_products[$i]]->getProductUrl();?>')" class="button" type="button"><span><span><span>Details</span></span></span></button>
<button onclick="setLocation('<?php echo $this->getUrl('')."/checkout/cart/add?product=".$displayed_products[$random_products[$i]]->getId()."&qty=1" ?>')" class="button"><span><?php echo $this->__('Add to Cart') ?></span></button>
</div>
</div>
</div></td>
<?php $k++; ?>
<?php endfor;?>
</tr>
</table>
</div>
</div>
</div>
<?php endif;?>
Now call block in your cms home page by adding following code:-
{{block type="catalog/product_list" category_id="3" num_products="8" template="catalog/random-product.phtml"}}

Magento - related product color swatches

I'm working with Magento EE v1.14 and i'm looking for a solution for when a user is viewing a product page to then drop swatches of related product colors if they are out of stock.
Screenshot: Highlighted out of stock related product color
Screenshot of HTML
PHP + HTML code:
<?php
$_base_product = $this->getProduct();
$base_product = Mage::getModel('catalog/product')->load($_base_product->getId());
$base_product_id = $base_product->getId();
$base_name = $base_product->getName();
$base_url = Mage::getBaseUrl();
$product_colors = Mage::getModel('catalog/product')->getCollection();
$product_colors->addAttributeToFilter('status',1); // 1 or 2
$product_colors->addAttributeToFilter('visibility',4); // 1.2.3.4
$product_colors->addAttributeToFilter('name', array('eq' => $base_name));
$product_colors->addAttributeToFilter('sku', array('neq' => $base_product->getSku()));
$product_colors_ids = $product_colors->getAllIds(); // get all products from the category
sort($product_colors_ids);
?>
<?php if(count($product_colors_ids) > 0) : ?>
<div id="product-color-options-wrapper">
<div id="product-color-options-container">
<label><?php echo $this->__('Color') ?> / <span style="font-weight: normal;"><?php echo $base_product->getAttributeText('color'); ?></span></label>
<div id="color-options-wrapper">
<?php $_swatch_img = $base_product->getMediaGalleryImages(false)->getItemByColumnValue('label', 'swatch') ?>
<?php if($_swatch_img) : ?>
<div class="current-product-wash-wrapper wash-wrapper">
<div class="current-product-wash-container wash-container">
<img src="<?php echo $this->helper('catalog/image')->init($base_product, 'small_image', $_swatch_img->getFile())->resize(33,30) ?>" alt="" title="<?php echo $base_product->getAttributeText('color') ?>" />
</div>
</div>
<?php else : ?>
<!-- <span><?php echo $base_product->getColor() ?></span> -->
<?php endif ?>
<?php foreach($product_colors_ids as $prod_id) : ?>
<?php $_sister_product = Mage::getModel('catalog/product')->load($prod_id) ?>
<?php
$_sister_prod_imgs = $_sister_product->getMediaGallery('images');
foreach($_sister_prod_imgs as $_sister_prod_img):
if($_sister_prod_img['label'] == 'swatch'):
$_swatch_img = $_sister_prod_img['file'];
endif;
endforeach;
?>
<?php if($_swatch_img): ?>
<div class="sister-product-wrapper wash-wrapper">
<div class="sister-product-container wash-container">
<a href="<?php echo $base_url ?><?php echo $_sister_product->getUrlKey() ?>">
<img src="<?php echo $this->helper('catalog/image')->init($_sister_product, 'small_image', $_swatch_img)->resize(33,30); ?>" alt="" title="<?php echo $_sister_product->getAttributeText('color') ?>">
</a>
</div>
</div>
<?php endif; ?>
<?php endforeach ?>
<div class="clear"></div>
</div>
</div>
</div>
<?php endif ?>
Any help would be appreciated! :D
**Solution:**Added an if statement to check for stock availability using the isAvailable() function, shown in screenshot.
Link to screenshot: https://gyazo.com/abf07ba0373877836571858ee129cc22

Page goes blank after adding to PHP foreach

Hello after I add some code to this PHP foreach the page goes blank and all I can see is a round black dot at the top left of screen.
My website is in Joomla3 and I am trying to customize a module. my site is http://get2gethersports.com
I have a recent post module that only shows the articles title.
that code is posted below
<?php if ($items) { ?>
<ul class="rsblog-recent-module unstyled<?php echo $params->get('moduleclass_sfx',''); ?>">
<?php foreach ($items as $item) { ?>
<li>
<a <?php echo $opener; ?> href="<?php echo JRoute::_('index.php?option=com_rsblog&view=post&id='.RSBlogHelper::sef($item->id,$item->alias).$Itemid,false); ?>">
<?php echo $item->title; ?>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>
I would like to add an image abocve like the blog feed on http://vape-co.com
So I navigated to the component and saw the call for the image. which is posted below:
<div class="rsblog-entry-content">
<?php if ($this->item->image) { ?>
<div class="rsblog-entry-image">
<img class="rsblog-entry-thumb img-polaroid" src="<?php echo JURI::root().'components/com_rsblog/assets/images/blog/'.$this->item->image; ?>?nocache=<?php echo uniqid(''); ?>" alt="<?php echo $this->escape($this->item->title); ?>">
</div>
<?php } ?>
but whenever i add it or a snippet of it to the previous code it breaks....
Any ideas why it is breaking the page and how to fix it?
I tried adding in new li tags. Just adding the PHP part above the a link etc...
CODE UPDATE----
<?php if ($items) { ?>
<ul class="rsblog-recent-module unstyled<?php echo $params->get('moduleclass_sfx',''); ?>">
<?php foreach ($items as $item) { var_dump($item);?>
<li>
<div class="rsblog-entry-content">
<?php if ($this->item->image) { ?>
<div class="rsblog-entry-image">
<img class="rsblog-entry-thumb img-polaroid" src="<?php echo JURI::root().'components/com_rsblog/assets/images/blog/'.$this->item->image; ?>?nocache=<?php echo uniqid(''); ?>" alt="<?php echo $this->escape($this->item->title); ?>">
</div>
</div>
<?php } ?>
<a <?php echo $opener; ?> href="<?php echo JRoute::_('index.php?option=com_rsblog&view=post&id='.RSBlogHelper::sef($item->id,$item->alias).$Itemid,false); ?>">
<?php echo $item->title; ?>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>
Try $item->image instead of $this->item->image
Correct code. Looks like it just needed some reduction.
<?php if ($items) { ?>
<ul class="rsblog-recent-module unstyled<?php echo $params -> get('moduleclass_sfx',''); ?>">
<?php foreach ($items as $item) { ?>
<li>
<?php if($item->image != '') ?>
<img src="components/com_rsblog/assets/images/blog/<?php echo $item->image;?>" alt="<?php echo $item->title. "logo";?>" width="100px"/>
<br/>
<a <?php echo $opener; ?> href="<?php echo JRoute::_('index.php?option=com_rsblog&view=post&id='.RSBlogHelper::sef($item->id,$item->alias).$Itemid,false); ?>">
<?php echo $item->title; ?>
</a>
</li>
<?php } ?>
</ul>
<?php } ?>

Get Magento Categories with Especific Sort of Admin Panel

I wrote the code below to put together a customized menu of categories. Everything works fine, but would like the order of the categories were the same order as defined in the administrator panel where there drap and drop functionality.
<?php
$subCats = Mage::getModel('catalog/category')->load(76)->getChildren();
$dispositosCatIds = explode(',',$subCats);
?>
<ul class="menu">
<?php $controleNum = 0; ?>
<?php foreach($dispositosCatIds as $dispositoCatId): ?>
<?php $aparelhoCat = Mage::getModel('catalog/category')->load($dispositoCatId); ?>
<?php if($aparelhoCat->getIsActive()): ?>
<li class="<?php print $controleNum ? '' : 'submenu first'; ?>"><a class="drop" href="<?php echo $aparelhoCat->getUrl(); ?>"> <span><?php echo $aparelhoCat->getName(); ?></span></a> <!--Begin 6 column Item -->
<div class="dropdown_6columns">
<div class="inner"><span class="title"><?php echo $aparelhoCat->getName(); ?></span>
<div class="col_2">
<div class="col_2 firstcolumn"><img src="<?php echo $aparelhoCat->getImageUrl(); ?>" alt="<?php echo $aparelhoCat->getName(); ?>" /></div>
</div>
<div class="col_4" style="margin-bottom: 20px;">
<?php echo $aparelhoCat->getDescription(); ?>
</div>
<div class="col_2 categorias-super"><span class="title_col">Produtos para <?php echo $aparelhoCat->getName(); ?></span>
<?php $subSubCats = $aparelhoCat->getChildrenCategories();?>
<?php if (count($subSubCats) > 0): ?>
<?php //$controleNumLI = 0; ?>
<ul style="list-style: none; float: none !important;">
<?php foreach($subSubCats as $_subcategory): //Rodando entre as categorias de Um dispositivo ?>
<?php if($_subcategory->getIsActive()): ?>
<li class="level1 <?php //print $controleNumLI ? '' : 'first'; ?>"> <?php echo $_subcategory->getName(); ?></li>
<?php //$controleNumLI += 1; ?>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
</div>
</div>
</li>
<?php $controleNum += 1; ?>
<?php endif; ?>
<?php endforeach; ?>
</ul>
I tried to use other modes (based here) can do this, but I could not. The problem that the function returns getChildren() is a string with IDs in ascending order.
Some Ideas?
This is the code I use to display category in a dropdown box in the order of the admin... the key is setOrder('path','ASC')
$categories = array();
$_categories = Mage::getModel('catalog/category')->getCollection()
->addAttributeToFilter('is_active',array('eq'=>true))
->addAttributeToSelect('level')
->setOrder('path','ASC')
->addAttributeToSelect('name')->load();
foreach($_categories as $cat){
$level = $cat->getLevel() - 1;
$pad = str_repeat("----", ($level > 0) ? $level : 0);
$categories[] = array('value' => $cat->getEntityId(), 'label' => $pad . ' ' . $cat->getName());
}
print_r($categories);
You could do something like this: create array tree from array list
I got it:
$dispositovosCategoryId = 76;
$dispositovosCategoryIds = Mage::getModel('catalog/category')->getCollection()
->addFieldToFilter('parent_id', array('eq'=>$dispositovosCategoryId))
->addAttributeToFilter('is_active',array('eq'=>true))
->addAttributeToSelect('level')
->setOrder('position','ASC')
->addAttributeToSelect('name','url','image')
->load();

Create a dynamic XML href in PHP with SimpleXML

I'm trying to create a link based on a URL variable using only the last five digits of its respective line of XML data.
For example, if the XML link is http://events.stanford.edu/events/213/21389 how can I create this link a href="e/?i=21389?
Here's my page, XML and code:
<?php
// Build the XML file path, using URL variable $c (above)
$c = $_GET['c'];
$p ="http://events-prod.stanford.edu/xml/byCategory/";
$e = "/mobile.xml";
$file = "$p$c$e";
$xml = simplexml_load_file($file);
?>
<h1><?php echo $xml->title; ?></h1>
Home
</div><!-- /header -->
<div data-role="content">
<?php // Only display if there are events ?>
<?php if (isset($xml->Event->title)) { ?>
<ul data-role="listview">
<?php foreach($xml->Event as $event) { ?>
<li>
<a href="<?php echo $event->link; ?>">
<?php if ($event->Media->url != null) { ?>
<img src="<?php echo $event->Media->url;?>" alt="<?php echo $event->title;?> thumbnail" />
<?php } ?>
<h3><?php echo $event->title; ?></h3>
<p><strong><?php echo $event->beginDate; ?> at <?php echo $event->beginTime; ?></strong></p>
<p><?php echo $event->locationText; ?></p>
</a>
</li>
<?php } ?>
</ul>
<?php } else { ?>
<?php echo '<p>There is currently nothing scheduled for ', $xml->title, '.</p>';?>
<?php } ?>
I'm using short tags, because I think you'll agree it's easier now to read the code as oppose to before.
<?
$controller ="http://events-prod.stanford.edu/xml/byCategory/";
$category_id = $_GET['c'];
$category_id = 0;
$xml = "/mobile.xml";
$url = $controller . $category_id . $xml;
$xml_object = simplexml_load_file($url);
?>
<div>
<h1><?= $xml_object->title ?></h1>
Home
</div>
<div data-role="content">
<? if (!empty($xml_object->Event->title)): ?>
<ul data-role="listview">
<? foreach($xml_object->Event as $event): ?>
<li>
<?
$pattern = '/[0-9]+$/';
$matches = array();
preg_match($pattern, $event->link, $matches);
$my_link = 'e/?i=' . $matches[0];
?>
<a href="<?= $my_link ?>">
<? if (!empty($event->Media->url)): ?>
<img src="<?= $event->Media->url ?>" alt="<?= $event->title ?> thumbnail" />
<? endif; ?>
<h3><?= $event->title ?></h3>
<p><strong><?= $event->beginDate ?> at <?= $event->beginTime ?></strong></p>
<p><?= $event->locationText ?></p>
</a>
</li>
<? endforeach; ?>
</ul>
<? else: ?>
<? echo '<p>There is currently nothing scheduled for ', $xml_object->title, '.</p>'; ?>
<? endif; ?>
</div>

Categories