Tag Archives: PHP

Magento : How to show new products in category list

In any normal e-commerce website, it is a good thing to obviously show which products are new. This way you attract attention of your regular visitors and maybe you sell more and you extend the lifetime customer value. Anyway, it is pretty normal to put these new products in front of others in the catalog, or at least to make them conspicuous.

Although Magento allows you to configure start and end dates for a product in order to show it as new, the default Magento template doesn’t show it. This is the goal of this mini-tutorial : to show you how to show new products among old ones in a category list.

In fact, this is not complicated, you only have to know how to do it. This information I’ve found on this forum (french) doesn’t seem to be well known over the internet, but giving such informations might help a lot improving the Magento Community. Anyway. I’ve summerized it, put it in a real example, and even provided it as a download for lazy developers.

First, in the product page of some product in Magento’s backend, insert starting and ending dates for its newness state. To do a test, put (of course) a date before today’s date, and a date which is later as today’s date.

The code to add to access newness dates of a product is the following :

load($_product->getID())->getNewsFromDate();
$newToDate = Mage::getModel(‘catalog/product’)->load($_product->getID())->getNewsToDate();

// Date and time (now)
$now = date(“Y-m-d H:m:s”);

if($newFromDate < $now && $newToDate > $now) {
echo “nv”;
}
?>

Variables $newFromDate and $newToDate get start and end dates of the active product during the loop. This data is only available if you did insert dates values in your product page. If you don’t see any change when you’ll reload the page, you may have not did this 🙂

The path of the file where to insert this code is named list.phtml is the following (just replace yourtheme by name of the theme you’re using, default is default one) :

/app/design/frontend/default/yourtheme/template/catalog/product/list.phtml

To add code for « list » mode, go to line 47, after this start of loop :

For « grid » mode, go to line 93, after the same code as for « list » mode, or almost.

In both cases, you can place the code wherever you want, as soon it is within the loop. Here is what end of loops look like :

If you followed this tutorial correctly, you should see at list a product with mention « This is new! ». If it doesn’t work, you still can download the file (Magento v1.3.2.4) down this page or ask help in comments of this article!

Check email address format (PHP & Javascript)

Here are two code snippets to verify email addresses, which is quite useful when you wish to validate a form with Javascript or PHP, avoiding users to write anything as email.

Verify email format with Javascript

Insert this code between <head> and </head> tags of your HTML document :



Insert a form between <body> and </body> tags :



Eventonsubmit calls checkMail() function and gives him text value of email field. Email field is identified by ID email.

Try this script online

Verify email format with PHP

This little PHP function allows you to check if the user wrote a valid email address that may exist. You call this function when you’re checking POST values after form submission.

function validMail($addr) {
if ((!ereg(“.+\@.+\..+”, $addr)) || (!ereg(“^[a-zA-Z0-9_@.-]+$”, $addr)))
RETURN FALSE;
else
RETURN TRUE;
}
// Use :
if(!validMail(‘infoaddress.com’)) {
echo “Your email address is invalid!”;
}

It won’t prove real existence of the email address, but it will avoid the user from writing stupid stuff.

!JoomlaComments dofollow links

!JoomlaComments is a well known Joomla! component that allows you to have comments on your Joomla! site articles. The links are by default set to nofollow and it’s not possible to set this in component’s configuration.

If you wish to make comments links in your blog dofollow, you’ll have to do a little hack within the component core itself :

Open this file : /components/com_comments/joscomment/comment.class.php and look for « nofollow », which should bring you to line 2293 :

$website = “ “;

Remove « nofollow » attribute :

$website = “ “;

That’s all!

Joomla, custom redirection after sign in

When a user signs in in Joomla, he is automatically redirected at homepage.

This article explains you how to add a hack in Joomla 1.5, to redirect the user to the page of your choice after he signed in. It may be useful, especially if you want the user to do a specific action (e.g. : to post an article, a picture, subscribe to your services, etc.). From back-end, you may specify a Joomla! page for redirection, but no custom URL.

I used Joomla 1.5.8 for this example, but it should be the same pattern for every other J1.5.x version.

Open this file :


[votre site]/components/com_user/controller.php

Look for this code line, that should be located at line 163, inside the login() function :

login() :

$mainframe->redirect( $return );

All you have to do is to replace $return by the URL where you want users to be redirected. For instance :

$mainframe->redirect( “http://www.guylabbe.ca” );

Dynamic RSS feeds

RSS feeds became essential for blogs and any other website that publishes content on a regulary basis. It’s a good way to broadcast your content and allow your visitors to follow your blog by suscribing to your feeds.

It allows also to submit your RSS feeds in RSS directory, which will give you deep links (other links than your homepage), in addition to bring new visitors from the directory because you show them interesting content before they have access to your website.

Most of CMS (as Joomla, WordPress, Dotclear, etc.) already have an embeded script that’ll generate RSS feeds for you. But if you own a dynamic website, scripted « by hand », you’ll have to do it by yourself…

Let’s say that you own a dynamic PHP website that provides articles from time to time. We’ll create a PHP function to extract articles from the database, then to write them in a XML file, which will be your RSS feed. This way, your RSS reed will update itself automatically.

GENERATE RSS FEED AUTOMATICALLY WITH URL REWRITING

To do it, we’ll use URL Rewriting, because it allows to do all that in a much cleaner way, by simulate the RSS file on demand, instead of constantly editing it in a real RSS file.

Create a .htaccess that you will place to root of your website, or edit the .htaccess file you may already own :


Options +FollowSymlinks
RewriteEngine on
# Link for RSS feed
RewriteRule ^rss\.xml$ /rss.php [L,NC]

With that rewriting, rss.php file will generate automatically the XML content of the RSS feed; it’ll simulate the file.

Create a file named rss.php. We extract, in the following example, last articles from an imaginary blog.

Structure of the table used in the example :


CREATE TABLE IF NOT EXISTS `blog` (
`id` mediumint(9) NOT NULL COMMENT ‘ID of the article’,
`texte` text NOT NULL COMMENT ‘Text of the article’,
`date` date NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT=’Articles of the blog’;

To insert into rss.php :

// MySQL connexion
$host = “localhost”; // normally, localhost
$user = “USERNAME”;
$pass = “PASSWORD”;
$bdd = “DB_NAME”;

@mysql_connect($host,$user,$pass) or die(“Connexion error: “.mysql_error());
@mysql_select_db(“$bdd”) or die(“Database selection error: “.mysql_error());

// Specify content type : XML
header(“Content-Type: text/xml”);

// MySQL query that extracts content from DB
$requete = “SELECT id, date FROM blog ORDER BY date DESC LIMIT 10″; // last 10 articles
$resultat = mysql_query($requete);

// XML writing
// header :
$sm = ”;
$sm .= ‘xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://www.google.com/schemas/sitemap/0.84
http://www.google.com/schemas/sitemap/0.84/sitemap.xsd”>’;

// Articles of the blog
while ($blog=mysql_fetch_array($resultat,MYSQL_ASSOC)) {
$xml = ‘‘;
$xml .= ‘‘;
$xml .= ‘RSS FEED TITLE‘; // Title of your RSS feed. For instance : Last articles of blog xyz
$xml .= ‘HTTP://WWW.YOURSITE.COM/‘; // Your website’s URL
$xml .= ‘‘.$title.’‘; // Your website’s description

$xml .= ‘‘;
$xml .= ‘YOUR_SITE/IMAGE.GIF‘; // An image, logo
$xml .= ‘IMAGE TITLE‘; // Normally the same thing as the title before
$xml .= ‘HTTP://WWW.YOURSITE.COM/‘; // your website’s URL
$xml .= ‘DESCRIPTION‘; // Description of you website (for image)
$xml .= ‘‘;
}

$i = 0;

foreach($news as $a) {

if($i < 12) { $id = $a['date']; $datexml = explode('-', $a['date']); $date2=date("D, d M Y H:i:s", mktime(0,0,0, $datexml[1],$datexml[2],$datexml[0])); $lien = "http://www.yoursite.com/articles.php?id=" . $id; // Link to your article (modify as your wish) $xml .= '‘;
$xml .= ‘‘.$a[‘titre’].’‘; // Article title
$xml .= ‘‘.$lien.’‘; // Link to article
$xml .= ‘‘.$lien.’‘; // Permalink
$xml .= ‘‘.$date2.’ GMT‘;
$xml .= ‘‘.strip_tags($a[‘txt’]).’‘; // Text of the article, removing HTML tags that it may contain
$xml .= ‘
‘;

$i++;
}
}

// end of XML
$xml .= ‘‘;
$xml .= ‘‘;
echo $xml;

Then, when you will try to reach http://www.votresite.com/rss.xml, rss.php will be called an a XML file will be generated and shown, with 10 last articles of your blog.

If you wish, it’s also possible to make a function with this code, and instead of simulating the RSS file with URL Rewriting, you can directly write into a rss.xml file. All you have to do is write something like this, to write in a real file :

// write file
$fp = fopen(“flux.xml”, ‘w+’);
fputs($fp, $xml);
fclose($fp);

Truncate string with PHP

It’s very simple, but useful; for instance, when you make a listing of articles on a page, but you only want to display a preview of the content of each article. Here is a small PHP function for text truncation :

function truncate_text($text, $nbrChar, $append=’…’) {
if(strlen($text) > $nbrChar) {
$text = substr($text, 0, $nbrChar);
$text .= $append;
}
return $texte;
}

// Now, we apply the function to a text :
echo truncate_text(‘this is a text I\’d like to truncate at fifty characters’, 50);

// which will have as result :
// this is a text I’d like to truncate at fifty cha…