Yet another blog (hopefully a useful one though)
Code
Magento – Handy code snippets
Mar 6th
Here’s a short list of magento codes to do some of the simple stuff. It’s a little empty at the moment but I’ll keep adding to it over time.
- Check if customer is logged in
<?php $_customer = Mage::getSingleton('customer/session')->isLoggedIn(); if ($_customer) { // do stuff } ?>
- Get product image
<?php echo $this->helper('catalog/image')->init($_product, 'image'); ?>
- Show image using current skin path (PHTML)
<img src="<?php echo $this->getSkinUrl('images/logo.png');?>" alt="logo" />
- Show image using current skin path (CMS)
<img src={{skin url="images/logo.png"}} />
- Show a custom block (CMS)
{{block type="catalog/product_featured" name="product_featured" as="product_featured" template="catalog/product/featured.phtml"}}
- Show a custom block (XML)
<block type="catalog/navigation" name="catalog.myblock" after="-" template="catalog/navigation/myblock.phtml"/> - Show CMS block (PHTML)
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('my_block_identifier')->toHtml() ?>
- Show short version of review summary
<?php echo $this->getReviewsSummaryHtml($_link,"short",true) ?>
Suggestions for any more helpful code snippets are more than welcome!
Ben
Creative Lead
MS Internet
Magento – Show image from a random product in a specific category
Mar 6th
A website we developed recently required some boxes on the homepage that link through to a specific category each, and each box needed to show an image from a random product from within that category. If you would like to do the same, here’s how it’s done:
- Create a PHTML file in your template folder, such as app/design/frontend/yourpackage/yourtheme/template/catalog/navigation/box.phtml
- Put this code in the file:
$images = array(); $catId=37; // put your category ID in here $products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect('image') ->addCategoryFilter(Mage::getModel('catalog/category')->load($catId)); Mage::getSingleton('catalog/product_status')->addSaleableFilterToCollection($products); // Only select products that are salable $products->load(); foreach($products as $product){ $images[] = $product->getImageUrl(); } if (sizeof($images) > 1) { $random_image = array_rand($images, 1); } else { $random_image = 0; } echo "<div class='box'><img src='" . $images[$random_image] . "'/></div>";
You can find the ID for your category by logging into the admin area and going to Catalog > Manage Categories and clicking on a category. You should see the ID come up next to the category name in the editable area.
- All you need to do now is specify where the box is shown. Open a layout file, such as app/design/frontend/yourpackage/yourtheme/layout/catalog.xml and use this layout update:
<reference name="left"><!-- change left to any structural block you want to target, such as right or content. --> <block type="catalog/navigation" name="catalog.box" template="catalog/navigation/box.phtml"/> <!--change the template path to wherever you put the template file --> </reference>
And that’s it! You should now have a block that shows an image from a random product within a specific category. You’ll need to do some styling to get it looking right mind but I hope this helps.
Ben
Creative Lead
MS Internet
Magento – Swap product image on thumbnail click
Mar 6th
One of the most frequent requests we get for Magento sites is to tame what the thumbnails do on the product page. Of course there are plenty of plugins for adding a lightbox of some sort, but if you simply want to swap out the image in the zoomer window for one of the thumbnails, here’s what you’ll need to do:
- Open app/design/frontend/yourpackage/yourtheme/template/catalog/product/view/media.phtml
- Go down to line 71 and change:
<li> <a href="#" onclick="popWin('<?php echo $this->getGalleryUrl($_image) ?>', 'gallery', 'width=300,height=300,left=50,top=50,location=no,status=yes,scrollbars=yes,resizable=yes'); return false;"> <img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(56); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>" /> </a> </li>
to
<li> <a href="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile()); ?>" title="<?php echo $_product->getName();?>" onclick="$('image').src = this.href; return false;"> <img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'thumbnail', $_image->getFile())->resize(70, 70); ?>" alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"/> </a> </li>
And that’s it! Your product image should now swap out for whichever thumbnail you click.
Credit to Scott from http://www.magentocommerce.com/boards/viewthread/6402/#t61131
Ben
Creative Lead
MS Internet
Magento SagePay Form
Feb 25th
Today we finally got our integration of Sage Pay Form for Magento. Sage Pay is the UK and Ireland’s most popular payment gateway and Magento is rapidly gaining popularity. We will be submitting our integration to Magento as a community app but it will be available from us until then.
UPDATE
The extension is now live in Magento Connect at http://www.magentocommerce.com/extension/3060/sagepay-formerly-protx-form as a free community extension.
To install enter the key in Magento Connect (from the page above) and the extension should install completely.
You will need a Sagepay account. You can get one HERE.
Then you need to enter the details in Magento > Admin > System > Configuration > Payment Methods > SagePay Form.
Next you must run a transaction in test mode using a SagePay test card found HERE and successfully refund this.
The , all you have to do is ask SagePay to let you “Go Live” and change the server target from “Test” to “Live”.
This is currently tested in v1.3.2.4 so we would be interested to hear whether it runs ok in other versions. There is no reason why it should not.
Happy Trading!
MS Internet Magento Easy Pre-Installer
Feb 18th
At MS Internet we are proud to use Magento as the base of the majority of our e-commerce projects. As a software Magento is very thoroughly built and provides a plethora or functions. The following is taken from the Magento site:
Marketing Promotions and Tools
- Flexible Coupons (pricing rules) with ability to restrict to stores, customer groups, time period, products, and categories.
- Catalog Promotional Pricing
Analytics and Reporting
- Admin Dashboard for Report Overview
- Abandoned Shopping Cart Report
- Best Customers Report by Total and Number of Orders
Search Engine Optimization
- Google Site Map
- URL Rewrites give full control of URL’s
- Meta-information for products and categories
Site Management
- Control multiple websites and stores from one Administration Panel with ability to share as much or as little information as needed
- Web Services API for easy integration between Magento and any third-party application
- One-Click Upgrades
- Google Website Optimizer Integration for A/B and Multivariate Testing
Catalog Management
- Batch Import and Export of catalog
- Google Base Integration
- Downloadable/Digital Products
- Advanced Pricing Rules and support for Special Prices (see marketing tools)
Catalog Browsing
- Layered / Faceted Navigation for filtering of products in Categories
- Layered / Faceted Navigation for filtering of products in Search Results
- Product comparisons
- Product Reviews
Checkout
- One-Page Checkout
- Checkout without account/Guest Checkout
- Shipping to multiple addresses in one order
Shipping
- Shipping to multiple addresses in one order
- Multiple shipments per order
- Free Shipping
Payment
- Integrated with Google Checkout (Level 2)
- Payment Extensions Available through Magento Connect
- Configurable to authorize and charge, or authorize only and charge on creation of invoices
Customer Accounts
- Re-orders from account
- Downloadable Products
- Recently ordered items
Order Management
- View, edit, create and fulfill orders from admin panel.
- Create one or multiple invoices, shipments and credit memos per order to allow for split fulfillment
The downside of Magento is that it is a huge application with almost 10,000 files. This makes the task of installing the base software quiet time consuming. If you have SSH access this can be done much more quickly than via ftp but many hosts will not allow this. So, we have created this Magento Pre-Installer to get and unpack the files and install the sample data.
This zip file contains one PHP script. To run simply upload to your web root. If you provide database credentials you can also install the sample data. This script fetches Magento version 1.3.2.4.
How to get ImageMagick to Convert pdf’s with GhostScript
Dec 14th
Ok, this is one for the nerds. I have spent most of today trying to figure out how to get ImageMagick to convert a pdf file to an image.
First I installed ImageMagick fine:
> wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz
> tar xvfz ImageMagick.tar.gz
> cd ImageMagick-6.5.8
> ./configure
> make
> make install
Then I installed the Imagick PECL module in cPanel.
I ran a test on the command line:
> /usr/local/bin/convert test.pdf test.jpg
And like Magick we had a jpg!
So, simple I thought, run an exec() function on the above and it will do the job. However…
Basically it didn’t work. It wouldn’t work with an Imagic script either:
<?php try { $im = new Imagick(); $im->readImage( "test.pdf" ); $im->pingImage("test.pdf"); $im->readImage( $image ); $im->setImageFormat( "jpg" ); $im->writeImage( 'test.jpg' ); echo 'Image Converted'; } catch(Exception $e) { echo $e->getMessage(); } ?>
Hmmm!?
So, I tried to simplify the situation and converted a jpg to a png whit the script as above and both worked perfectly. So I checked the Apache error log and found that aparently “gs” did not exist. So I installed Ghostscript (which is apparently required for converting pdf’s and ps’s with exact same procedure as for Imagemagick except with the appropriate ghostscript tar.gz file. And…
Still nothing!
So, I did a bit of trawling and it turned out that Apache did not have the path to Ghostscript in the environmental path. To cut a fairly long story short I could not get httpd.conf, php.ini or .htaccess to cooperate in adding the path so I created a symbolic link from a directory already in the Apache path (/usr/bin/) to the actual location with:
> ln /usr/local/bin/ /usr/bin/
And by some minor miracle it worked!
So, if you have Imagemagick and Ghostscript installed and images work fine but pdf’s will not convert (like about 100 people I found in google-land), find your path with:
<?php echo getenv("PATH"); ?>
Then run:
> whereis gs
To find GhostScript (gs)
and run:
> ln /usr/local/bin/ /usr/bin/
Or equivalent.
Enjoy!
How to fix PushIt WordPress plugin wp-admin 500 Error
Nov 14th
We had a client with a mysterious plugin related server error when they tried to access thair admin dashboard with output:
/*pushit_user_row_phone_variable_define_start*/ $phone = isset($user_object->phone_number) ? get_user_mobile($user_object) : “not set”; /*pushit_user_row_phone_variable_define_stop*//*pushit_user_row_phone_variable_insert_start*/break; case ‘phone’: $r .= “$phone”;/*pushit_user_row_phone_variable_insert_stop*/
They said that the problem had happened immediately after installing the PushIt plugin. So, we took the usual action and went into the database and ran:
SELECT *
FROM wp_options
WHERE option_name = ‘active_plugins’
and removed the content to disable all plugins.
Still no admin!
So, we removed the wp-content/plugins/pushit/ folder via ftp.
STILL NO ADMIN!!
So we scanned the code for instances of “pushit” and fount three.
- In /wp-admin/user-edit.php
- In /wp-admin/user-new.php
- In /wp-admin/includes/template.php
These files first of all lacked PHP open and close tags hence the server error but all looked rather small.
So we downloaded the latest WordPress version and opened these files. It looks like the idiot (yes I know it’s a strong word but who ever they are they are IDIOTS) had code replacing rather than inserting into these files. We hastilly overwrote these three files and Voila! no problems.
In quick summary: Do not ever install PushIt!! Tell everybody you know not to install PushIt!! If you know the person that wrote PushIt – give them a swift kick in the *^”^%£*^s.
Utility PHP Email Detection Script
Nov 14th
I wrote a little function to check the formatting of an email so I thought I would share it with the world:
<?php function is_email($email) { if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){ return 1; } else { return 0; } } ?>
Ajax filled form field errors in firefox and some IE wierdness too
Nov 14th
I spent ages looking for the answer to this one and it ended up really simple so I thought I would share it.
We had a web form where a select field was chosen. Then a second select was populated by ajax depending on the value of the first select. All pretty standard except that in firefox the second select just disappeared! After a whole bunch of wild theories about form encoding and other crazy stuff it turned out that the problem was in the validation. In order for a form to be valid XHTML the <form> tags have to lie OUTSIDE the <table> tags. When this is done wrong firefox, being pernickety, decides that as the code is not valid and the page was built dynamically it cannot cope so ignores the second <select> completely. All very stupid!
As for IE, we found out today that if you AJAX in only the <option> tags the second select will not work. However if you AJAX in the whole <select> it does! Crazy!